I’ve just recently attempted to upload an entire directory up to sharepoint. I did initially try doing this using WebDAV but the speed was unimaginable slow (30 – 40 secs for a 1KB gif image). I didn’t want to upload the images through the browser as you can only do 100 at a time (I had ~3,500 images plus ~4,000 documents).
So I looked at copying over the files using the sharepoint object model! It turns out that this is speedy fast and works a treat! There’s an MSDN article I used as my basis but I’ve made a few changes so it uploads a whole directory instead of just a single file. Here’s how you do it:
public void UploadImages()
{
this.CopyDirectory(@"\\some\server\images", "PublishingImages");
this.CopyDirectory(@"C:\ImagesFolder\ImagesToUpload", "PublishingImages");
}
private void CopyDirectory(string frm, string to)
{
var serveraddress = "http://server:80/";
using (var web = new SPSite(serveraddress + to).OpenWeb())
{
if (!web.Exists)
{
throw new Exception("Web doesn't exist here");
}
var di = new DirectoryInfo(frm);
var fileInfos = di.GetFiles("*.*", SearchOption.TopDirectoryOnly);
foreach (var fileInfo in fileInfos)
{
this.UploadFile(fileInfo.FullName, web);
}
}
}
private void UploadFile(string srcUrl, SPWeb web)
{
if (!File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}
byte[] contents;
using (FileStream fStream = File.OpenRead(srcUrl))
{
contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int) fStream.Length);
fStream.Close();
}
string filename = srcUrl.Substring(srcUrl.LastIndexOf("\\") + 1);
if (!IsValidFileName(filename))
{
throw new Exception(filename + " is not a valid filename. Please review and try again.")
}
var file = web.Files.Add(filename, contents)
file.Update();
}
private static bool IsValidFileName(string filename)
{
if (filename.Contains("..") || filename.EndsWith(".") || filename.StartsWith("."))
{
return false;
}
if (filename.IndexOfAny(new[] { '\"', '#', '%', '&', '*', ':', '<', '>', '?', '\\', '/', '{', '|', '}', '~' }) > -1)
{
return false;
}
if (filename.Length > 128)
{
return false;
}
return true;
}