In this article, I am going to add a document through code to a SharePoint document library. I am going to use SharePoint object model to add document.
I do have a document library called “My Documents”. I am going to add document to this library. Currently the documents in library are as below.
- User will enter full path of the file to be uploaded in the textbox.
- File will get uploaded with the name uploadaedfromcode.doc in the document library.
- Window form contains one textbox and one button.
Add the reference of Microsoft.SharePoint.dll in the window application.
Form1 : Form
void Form1_Load(object sender, EventArgs e)
void btnUpload_Click(object sender, EventArgs e)
string filename = txtUpload.Text;
SPSite _MySite = new
SPWeb _MyWeb = _MySite.OpenWeb();
FileStream fstream = File.OpenRead(txtUpload.Text);
byte content = new
fstream.Read(content, 0, (int)fstream.Length);
MessageBox.Show(“File Saved to name called uploadedfromcode”);
- SPSite is returning the site collection. URL of the site collection is being passed to the constructor.
- SPWeb is returning the top level site.
- FileStream is reading the file from the path provided in the text box.
- I am reading the filestream in the byte.
- I am adding the file in the document library. There are two parameter passed. First parameter is URL of the document library. Second parameter is byte read from the file stream.
- I am giving name of the file is uploadedfromcode.doc
In this article, I have shown how to upload a file in SharePoint document library. Thanks for reading.
Leave a Reply