Programmatically create documents in Libraries

One thing that it can be useful to do sometimes is create documents in a library, possibly with some metadata. I find that I sometimes end up doing this from a console app, just to put in some example information:

string filePath = ...
string newName = ...
SPList library = ...
using (FileStream fs = new FileStream(filePath,FileMode.Open)){
SPFile file = library.RootFolder.Files.Add( newName ,fs, true );
SPListItem item = file.Item;
item["SomeField"] = "SomeValue";
item.Update();
}

Advertisement
Programmatically create documents in Libraries