Posts Tagged file

Upload file in MOSS / SharePoint using code

It is easy and simple to upload a file in the document library of MOSS / SharePoint. The code for upload the file in C# is as under: 

SPSite sp = new SPSite(“URL of the site collection”);     

SPWeb site = sp.OpenWeb();      

SPFolder folder = site.GetFolder(“Document Library Name”);     

SPFileCollection files = folder.Files; FileStream fStream = File.OpenRead(“C:\\upload.doc”); //path of the file to upload     

byte[] contents = new byte[fStream.Length];     

fStream.Read(contents, 0, (int)fStream.Length);     

fStream.Close();      

Hashtable MetaDataTable = new Hashtable();     

MetaDataTable.Add(“Comments”, “Hello World”);      

SPFile currentFile = files.Add(“URL of the document library/upload.doc”, contents, MetaDataTable, true); 

You can addd the meta data as well by using Hash Table. We have populated the “Comments” column with “Hello World”. 

With or without using the following code

 SPListItem doc = currentFile.Item;  

We can do a lot of things with the uploaded file.

For more information, visit the Microsoft link. It provides more information about the error checking and other.

Comments (20)