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

8

54

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.

Petrinapetrine answered 22/1, 2009 at 8:57 Comment(1)
duplicate of #21509273Foppery
B
74

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();
    }
}
Buskined answered 22/1, 2009 at 11:1 Comment(9)
Chadworthington, SPSite is part of Microsoft.SharePoint namespace, so you need to add reference to Microsoft.SharePoint.dll. Assuming you are developing on the Server, the dll can be found here: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.SharePoint.dllBuskined
Wait a sec... this code will only work in a box joined to the farm, correct? In any other box, it needs to use msdn.microsoft.com/en-us/library/ee857094.aspxConsuelaconsuelo
@Consuelaconsuelo You are correct. The client APIs are the way to access the SharePoint server from the outside. Also see msdn.microsoft.com/en-us/library/ee537564.aspxQuartis
You dont need to call myLibrary.Update(); file adds after Files.Add(..)Masbate
@Henrique Zacchi, I dont see any folder named web server extensions in the path "C:\Program Files\Common Files\microsoft shared". Do I need to install sharepoint in my machine?Schaffhausen
This worked well for me, except that I had to use a "using" on the filestream when deleting the file afterwards (for the delete to work). I changed it to: using (FileStream fileStream = File.OpenRead(fileToUpload)) { // Upload document SPFile spfile = doclib.Files.Add(fileName, fileStream, replaceExistingFiles); }Menispermaceous
This is not a good solution. It needs to be run as someone who is both a DBO and a SP Farm administrator, which is a ridiculous over-priv for the task of uploading a file.Methodist
I want to do same thinking to create a Document and host to SharePoint using .net Core MVCWholism
There are numbers of Sharepoint Libraries. Can you mention correct link which library? and it is far better if you can mention which version which is stable.Junina
L
13

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

Lingerfelt answered 5/12, 2012 at 15:34 Comment(0)
E
10

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);
}
Elope answered 13/7, 2014 at 12:22 Comment(3)
Hello, I am getting below error. System.NotSupportedException: The given path's format is not supported. at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) can you please help?Publicize
Which row gives you this exception?Elope
What is name of library? is it available at nuget?Junina
C
8
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");
        }
    } 
} 
Chinn answered 10/10, 2012 at 15:58 Comment(1)
+1 for CheckIn if statements. Consider to not updating the myLibrary. It can cause concurrency conflicts.Scolex
C
6

As an alternative to the webservices, you can use the 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 SharePad project on CodePlex.

Condone answered 22/1, 2009 at 19:25 Comment(0)
A
6
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;
}
Alkalosis answered 8/5, 2019 at 8:23 Comment(2)
Please add some explanation to your answerSupposed
The best one so far.Vorlage
L
0

I think using an App is the safest way to go because using username and password caused lots of problems to me.

  1. Register an app:

https://YOUR_TENANT_NAME.sharepoint.com/sites/YOUR_SITE_NAME/_layouts/15/AppRegNew.aspx

  1. Grant permission:

https://YOUR_TENANT_NAME.sharepoint.com/sites/YOUR_SITE_NAME/_layouts/15/appinv.aspx

Copy ClientID and ClientSecret and save it into your App.config file

<appSettings>
  <add key="ClientId" value="YOUR_CLIENT_ID" />
  <add key="ClientSecret" value="YOUR_CLIENT_SECRET" />
</appSettings>

Detailed instructions: https://www.sharepointdiary.com/2019/03/connect-pnponline-with-appid-and-appsecret.html

You will need this nuget package:

Install-Package AppForSharePointOnlineWebToolkit -Version 3.1.5

If you got any errors while using the nuget package, install the library from error message. Probably there is a better way than using this package but it is what I got.

    static void Main(string[] args)
    {
        const string siteUrl = "https://YOUR_TENANT_NAME.sharepoint.com/sites/YOUR_SITE_NAME";
        var localFilePath = @"C:\your_file.txt";
        var libraryName = "Documents";
        UploadFileToSharePoint(siteUrl, localFilePath, libraryName);
    }

    private static void UploadFileToSharePoint(string siteUrl, string localFilePath, string libraryName)
    {
        var realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));

        //Get the access token for the URL.  
        var accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
        
        //Create a client context object based on the retrieved access token
        using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
        {
            var fci = new FileCreationInformation
            {
                Overwrite = true,
                Content = System.IO.File.ReadAllBytes(localFilePath),
                Url = Path.GetFileName(localFilePath)
            };
            
            var library = ctx.Web.Lists.GetByTitle(libraryName);
            var uploadFile = library.RootFolder.Files.Add(fci);
            
            ctx.Load(uploadFile);
            ctx.ExecuteQuery();
        }
    }
Lutherlutheran answered 12/10, 2023 at 12:13 Comment(0)
V
-1

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!

Vesical answered 24/2, 2020 at 21:7 Comment(2)
its June 2023, do you think this thread can serve as a good guide to go from FileShare to SharePoint upload, can be it done in stand alone C# script via SSIS? or I need create whole project ? Thanks MarioNeolatin
Careful! Dodgy link!!Jaime

© 2022 - 2024 — McMap. All rights reserved.