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);     


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.



  1. hyze said

    hi Farhan,

    Can i know why we need to make a custom code for uploading file instead of using the built in. Just wonder why? 🙂

  2. farhanfaiz said

    hi Hyze,

    It was a requirement from one of our customers that documents are required to be uploaded as an attachement and we fail to find any attachement column.

    Further, our client refused to go for the lookup column. The process of using built in upload functionality for attachement purpose was not fast enough for the client. For further details kindly visit the link:


    Do let me know in case you requird any other information.

  3. hyze said

    Thanks for the quick reply.

    No. I just wonder why we need to usie an in line code since you mentioned Upload file to Sharepoint Site. If for the attachment, there is an icon that you can attach you attachment in a list if not mistaken.

    btw, great job to you since you are the first one blogger from malaysia and Malay in MOSS so far. i havent seen any.

  4. farhanfaiz said

    The problem was that we need to add attachement in a document library. We use ID of the documents in the URL and wrote in line code to upload the files against the ID of the document in the URL.

    Hopefully you get my point.

  5. lavez said

    it works! thank you for your help. now i’m looking for a way to populate hashtable with parameter generated from other web part. Any idea?
    thank you again…


  6. mari said

    the code used to work, but I tested it today and doesn’t work anymore.
    When I try to upload a file in the sharepoint server, it works. But when I try it in another computer it returns error telling that the path wasn’t found.
    any ideas?


  7. mari said


    When I try to upload files in the server that is running the sharepoint, the code works fine, but when I try it in another computer, it returns error. It tells that can’t access the folder that contains the file to be uploaded.
    Could u help me?

  8. Anonymous said

    Can you provide the path of the folder


  9. Elmar Rath said

    Hello Farhan,

    I’ve the following problem. I have a running webapplication, so that our external sales guys could get informations about our customers. Now my chief wants to add a WSS3.0 to our system so that my colleges could upload their correspondence and documenst to the WSS. My chief wants further that the sales guys only have to use the login of our existing webapplication.
    So my chief wants that the guys have only to press the Upload-Button and then lets the magic work. When the upload was successfull I should only return the new file url on the WSS. The authentification mode should be “form based”, because our current web application should run on an other server and windows domain then the WSS and its IIS.

    Now I’m not sure how I could handle the login and how to tell your code that the user “xyz”, has permission to post his documents in folder “abc”. I hope you could give me a hint.
    We will use the same passwords and usernamens for WSS as we use in our existing system.



  10. farhanfaiz said

    If you are looking for a desktop application, I think that using web services will help you in this regard but I am not sure that will it work for Form base authentification. 😦

    Following links may help you in this regard:



    Do let mw know if this works or 😦

  11. Bryant Duke said

    Do you know if this will work for a Custom List? I have built a custom application in C# and .aspx pages which create, delete and modify list items in the background without the user ever seeing the actual Sharepoint List. We wanted to avoid the standard Sharepoint List hassels.


  12. Farhan Faiz said

    Although I have not tested this, but, I find no reason that this will not work as long as one is using Object Model

  13. Bryant Duke said

    I used the following code to upload a file to the Custom List from a Popup Window using C# and it works fine. All of the byte stream work was already done for me in the Object.

    if (m_fileUpload.HasFile)
    SPList list = aaitem.ParentList;
    String url = aaitem.ParentList.RootFolder.ServerRelativeUrl.ToString();
    string FileNameSave = m_fileUpload.FileName.ToString();
    aaitem.Attachments.Add(FileNameSave, m_fileUpload.FileBytes);

    Thanks for the post which got me started.


  14. Bryant Duke said

    By the way, I forgot to mention the object I used:

    protected FileUpload m_fileUpload;
    using (SPSite site = new SPSite(“https://url/”)) {
    using (SPWeb web = site.OpenWeb(“website”)) {
    SPListItemCollection aalistitems = web.Lists[“CustomListName”].Items;
    aaitem = aalistitems.GetItemById(existingItemID);

    if (m_fileUpload.HasFile)
    string FileNameSave = m_fileUpload.FileName.ToString();
    aaitem.Attachments.Add(FileNameSave, m_fileUpload.FileBytes);



  15. venu said

    The Web application at http://localhost could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL

    I am trying to upload a pdf to sharepoint (wss) from an external webpage and I get this error as above. My code is below: Can you help with the proper sample if possible.

    string[] file = filePath.PostedFile.FileName.Split(‘\\’);
    int length = file.Length;

    // get the name of file from path
    string fileName = file[length – 1];

    Stream fStream = filePath.PostedFile.InputStream;

    // Read file in a byte array
    byte[] MyData= new byte[fStream.Length];

    SPSite mySiteCollection = new SPSite(“http://localhost”);

    //Grab the rootSite
    SPWeb myWeb = mySiteCollection.RootWeb;

    //Get the folder that should store the document
    SPFolder folder = myWeb.Folders[“CRMEnquiries”];

    folder.Files.Add(folder.Url + “/” + fileName, MyData,true);

  16. Farhan Faiz said


    First try to do this excluding RootWeb by specifying URL of root. Second, check Alternate Access Maaping settings.

    Do let me know.


  17. nagaraju said

    HI ,
    i have a different requirement ,i have one intranet site nad internet site so ,when i upload a documnt in intranet site the same document is automatically upload into the internet(moss site) site.

    thanks in advance.

  18. Farhan Faiz said

    Please open connection to internet site as well and upload the document twice.

    Do let me know if further assistance is desired.



  19. This was really useful on a sp2010 project we did – cheers Farhan!

  20. Maybe you could edit the webpage name title Upload file in MOSS / SharePoint using code farhanfaiz's Weblog – SharePoint 2003/2007/2010 to more better for your content you create. I liked the post withal.

RSS feed for comments on this post · TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: