Sunday, 25 December 2011

Little tool to extract all files out of Sharepoint

We’ve been using Microsoft Sharepoint here at Plaxo to organize our projects and files. For those who have used Sharepoint, you know it’s a love/hate relationship

Anyways, we needed to get a copy of all the files in our Sharepoint site recently. Looking around on the web, we found a few solutions, but couldn’t really find one that did exactly what we wanted. So, I wrote up a quick little app to grab all the files we needed out of Sharepoint, while preserving Sharepoint’s directory structure. It’s a command line tool and it doesn’t have any options.

It’s really not that hard; here’s the source in case you’re interested:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;

// replace this string with your Sharepoint content DB connection string
string DBConnString = “Server=YOURSHAREPOINTSERVER;Database=CONTENTDATABASE;Trusted_Connection=True;”;

// create a DB connection
SqlConnection con = new SqlConnection(DBConnString);
con.Open();

// the query to grab all the files.
// Note: Feel free to alter the LeafName like ‘%.extension’ arguments to suit your purpose
SqlCommand com = con.CreateCommand();
com.CommandText = “select DirName, LeafName, Content from Docs where (LeafName like ‘%.doc’ or LeafName like ‘%.xls’ or LeafName like ‘%.pdf’ or LeafName like ‘%.ppt’) and Content is not NULL”;

// execute query
SqlDataReader reader = com.ExecuteReader();

while (reader.Read())
{
// grab the file’s directory and name
string DirName = (string)reader["DirName"];
string LeafName = (string)reader["LeafName"];

// create directory for the file if it doesn’t yet exist
if (!Directory.Exists(DirName))
{
Directory.CreateDirectory(DirName);
Console.WriteLine(“Creating directory: “ + DirName);
}

// create a filestream to spit out the file
FileStream fs = new FileStream(DirName + “/” + LeafName, FileMode.Create, FileAccess.Write);
BinaryWriter writer = new BinaryWriter(fs);

// depending on the speed of your network, you may want to change the buffer size (it’s in bytes)
int bufferSize = 1000000;
long startIndex = 0;
long retval = 0;
byte[] outByte = new byte[bufferSize];

// grab the file out of the db one chunk (of size bufferSize) at a time
do
{
retval = reader.GetBytes(2, startIndex, outByte, 0, bufferSize);
startIndex += bufferSize;

writer.Write(outByte, 0, (int)retval);
writer.Flush();
} while (retval == bufferSize);

// finish writing the file
writer.Close();
fs.Close();

Console.WriteLine(“Finished writing file: “ + LeafName);
}

// close the DB connection and whatnots
reader.Close();
con.Close();

Here’s my VS.NET 2005 project file. If you need help with the code, please let me know.
posted by furqan ahmed

No comments:

Post a Comment