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.

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?
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:
http://farhanfaiz.wordpress.com/2008/01/21/in-line-code-to-upload-supportive-documents/
Do let me know in case you requird any other information.
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.
Congrat
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.
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…
Alessandro
mari said
hi,
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?
thanks
mari said
hi,
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?
thanks
Anonymous said
Can you provide the path of the folder
Regards,
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.
Regards
Elmar
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:
http://www.codeguru.com/csharp/csharp/cs_webservices/tutorials/article.php/c8805/
http://www.developer.com/services/article.php/3492456
Do let mw know if this works or
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.
Bryant
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
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);
aaitem.Update();
}
Thanks for the post which got me started.
Bryant
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);
aaitem.Update();
}
}
}
Sorry
Bryant
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);
Farhan Faiz said
Venu,
First try to do this excluding RootWeb by specifying URL of root. Second, check Alternate Access Maaping settings.
Do let me know.
Regards,
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.
raju.
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.
Regards,
farhan
Sharon @ SharepointCode.co.uk said
This was really useful on a sp2010 project we did – cheers Farhan!
Pointer Men's Basketball said
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.