In one my projects we had a requirement to programmatically upload document to a SharePoint’s document library.
Below is the code we used to achieve that.
// documentFileUrl would be :- http://server_name/doclibraryname/foldername (till doclibrary name or folder name to which doc
// is to be uploaded
// bytes :- byte array of the content
// fileNameWithExtension would be :- test.docx
// listName :- the display name of the list
public void UploadDoctofolder(string docfileurl, string fileNameWithExtension, byte[] bytes, string listName)
{
WebRequest request = WebRequest.Create(docfileurl + "/" + fileNameWithExtension);
request.Credentials = this.credentials;
request.Method = "PUT";
byte[] buffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
{
using (MemoryStream ms = new MemoryStream(bytes))
{
for (int i = ms.Read(buffer, 0, buffer.Length); i > 0; i = ms.Read(buffer, 0, buffer.Length))
{
stream.Write(buffer, 0, i);
}
}
}
WebResponse response = request.GetResponse();
response.Close();
}
Hope it helps!
Discover more from Nishant Rana's Weblog
Subscribe to get the latest posts sent to your email.

I have been doing this in powershell for a while, Would you happen to know a way to create folders without using the SharePoint API?
LikeLike