How do you upload a file to a document library in sharepoint?

C#SharepointUpload

C# Problem Overview


How do you programmatically upload a file to a document library in sharepoint?

I am currently making a Windows application using C# that will add documents to a document library list.

C# Solutions


Solution 1 - C#

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 
        myLibrary.Update();
    }
}

Solution 2 - C#

if you get this error "Value does not fall within the expected range" in this line:

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

use instead this to fix the error:

SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;

Use always URl to get Lists or others because they are unique, names are not the best way ;)

Solution 3 - C#

With SharePoint 2013 new library, I managed to do something like this:

private void UploadToSharePoint(string p, out string newUrl)  //p is path to file to load
{
	string siteUrl = "https://myCompany.sharepoint.com/site/";
	//Insert Credentials
	ClientContext context = new ClientContext(siteUrl);

	SecureString passWord = new SecureString();
	foreach (var c in "mypassword") passWord.AppendChar(c);
	context.Credentials = new SharePointOnlineCredentials("myUserName", passWord);
	Web site = context.Web;

	//Get the required RootFolder
	string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
	Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

	//Create new subFolder to load files into
	string newFolderName = baseName + DateTime.Now.ToString("yyyyMMddHHmm");
	barFolder.Folders.Add(newFolderName);
	barFolder.Update();

	//Add file to new Folder
	Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
	FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
	currentRunFolder.Files.Add(newFile);
	currentRunFolder.Update();

	context.ExecuteQuery();

	//Return the URL of the new uploaded file
	newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
}

Solution 4 - C#

string filePath = @"C:\styles\MyStyles.css"; 
string siteURL = "http://example.org/"; 
string libraryName = "Style Library"; 

using (SPSite oSite = new SPSite(siteURL)) 
{ 
	using (SPWeb oWeb = oSite.OpenWeb()) 
	{ 
		if (!System.IO.File.Exists(filePath)) 
			throw new FileNotFoundException("File not found.", filePath);                     

		SPFolder libFolder = oWeb.Folders[libraryName]; 

		// Prepare to upload 
		string fileName = System.IO.Path.GetFileName(filePath); 
		FileStream fileStream = File.OpenRead(filePath); 

		//Check the existing File out if the Library Requires CheckOut
		if (libFolder.RequiresCheckout)
		{
			try {
				SPFile fileOld = libFolder.Files[fileName];
				fileOld.CheckOut();
			} catch {}
		}

		// Upload document 
		SPFile spfile = libFolder.Files.Add(fileName, fileStream, true); 

		// Commit  
		myLibrary.Update(); 

		//Check the File in and Publish a Major Version
		if (libFolder.RequiresCheckout)
		{
				spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
				spFile.Publish("Publish Comment");
		}
	} 
} 

Solution 5 - C#

As an alternative to the webservices, you can use the http://msdn.microsoft.com/en-us/library/ms479623.aspx">put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).

For a reference application that explains the use of Frontpage RPC, see the http://www.codeplex.com/sharepad">SharePad</a> project on CodePlex.

Solution 6 - C#

try
{
	//Variablen für die Verarbeitung
	string source_file = @"C:\temp\offer.pdf";
	string web_url = "https://stackoverflow.sharepoint.com";
	string library_name = "Documents";
	string admin_name = "[email protected]";
	string admin_password = "Password";

	//Verbindung mit den Login-Daten herstellen
	var sercured_password = new SecureString();
	foreach (var c in admin_password) sercured_password.AppendChar(c);
	SharePointOnlineCredentials credent = new 
	SharePointOnlineCredentials(admin_name, sercured_password);

	//Context mit Credentials erstellen
	ClientContext context = new ClientContext(web_url);
	context.Credentials = credent;

	//Bibliothek festlegen
	var library = context.Web.Lists.GetByTitle(library_name);

	//Ausgewählte Datei laden
	FileStream fs = System.IO.File.OpenRead(source_file);

	//Dateinamen aus Pfad ermitteln
	string source_filename = Path.GetFileName(source_file);

	//Datei ins SharePoint-Verzeichnis hochladen
	FileCreationInformation fci = new FileCreationInformation();
	fci.Overwrite = true;
	fci.ContentStream = fs;
	fci.Url = source_filename;
	var file_upload = library.RootFolder.Files.Add(fci);

	//Ausführen
	context.Load(file_upload);
	context.ExecuteQuery();
	
	//Datenübertragen schließen
	fs.Close();
}
catch (Exception ex)
{
	MessageBox.Show(ex.Message, "Fehler");
	throw;
}

Solution 7 - C#

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdytView Question on Stackoverflow
Solution 1 - C#Henrique ZacchiView Answer on Stackoverflow
Solution 2 - C#Ricardo VieiraView Answer on Stackoverflow
Solution 3 - C#Uziel SulkiesView Answer on Stackoverflow
Solution 4 - C#user1735365View Answer on Stackoverflow
Solution 5 - C#Paul-JanView Answer on Stackoverflow
Solution 6 - C#Eren PakView Answer on Stackoverflow
Solution 7 - C#XtremexploitView Answer on Stackoverflow