Blog Archives

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.