Monday, June 2, 2008

Adding local file to site's folder

Hi All,

Here is a way how you can add your local files to SPFolder. All you need to do is just read the local file as a streams and then just called Files.Add Method to add a file in the Folder.

SPWeb objWeb = SPContext.Current.Web;
objWeb.AllowUnsafeUpdates = true;
SPFolderCollection objFolderColl = objWeb.Folders;
foreach (SPFolder objFolder in objFolderColl)
{
if (objFolder.Name == "Groups Document")
{
FileStream fStream = File.OpenRead("C:\\groups.txt");
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

objFolder.Files.Add("Testdoc.doc", contents);
objFolder.Update();

break;
}
}

objWeb.AllowUnsafeUpdates = false;

That's it. Your job is done.

2 comments:

Unknown said...

Hi SPKings

Your solution is a little incomplete.

When considering one might be able to add specific metadata (such as a specific content type) before adding the item to ensure property values exists when events (e.g. ItemAdded) are fired.

More complete might be:

Hashtable hashTable = new Hashtable(); hashTable.Add("ContentTypeId", -ContentTypeId-);
hashTableProperties.Add("Title", -Title-);

objFolder.Files.Add("Testdoc.doc", contents, hashTable);

In the above example, all the corresponding content type specific events will fire on item creation (which was the solution i was looking for).

Thanks for the informative blog!

Parth Patel said...

Hi arnhem,

thanks to you for sharing your thought and solution.




Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com