Programmatically loading a folder of files into a SharePoint Image library

I keep having to do this and I keep forgetting how to do it.  So, how to take a folder full of image files and programmatically upload them all into a SharePoint library, and set some metadata.

private static void ImportImages(SPWeb web)
  var imageList = web.Folders[IMAGES_LIST_NAME]; //Get our image library
  var files = Directory.GetFiles(IMAGES_DIRECTORY]; //Get all files in the folder
  foreach (var file in files)
    if (File.Exists(file))
      string filename = file.Remove(0, _imagesDirectory.Length+1); //Strip the path off the name
      Console.Write("Uploading {0}...", filename);
      FileStream fStream = File.OpenRead(file);
      SPFile spFile = imageList.Files.Add(filename, fStream, true); //The true means "overwrite existing"
      Console.Write("done...writing metadata...");
      SPListItem item = spFile.Item; //Get our recently created file as a ListItem
      item["Title"] = filename; //Set the Metadata in the usual way
      item["Alternative Text"] = filename;

Works for documents too.

Posted on May 2, 2014, in SharePoint and tagged , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: