Upload a file to a document library in SharePoint 2010 programmatically in client-server application

I am using below code to upload the file in SharePoint 2010 Library

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

This worked well through my machine. But when I deploy it on server and used the below snippet to upload file in library from my machine, it gives error. It is not getting the file location (C:\YourFile.txt) from local(client) machine.

Upvotes: 0

Views: 4524

Answers (2)

Ashish Madkaikar
Ashish Madkaikar

Reputation: 129

When you run on the server your code runs under a different account (apppool identity) which does not have the permission to read C drive.

I dont know why would you want to read and upload a file from the same server, looks like you are simply testing Sharepoint Object Model then it is ok

If you are expecting some other app or service to keep an updated file for Sharepoint , it should be moved to the web directory i.e \wwwroot\wss\VirtualDirectories\80 and then use your code to read and update your doc lib (myLibrary) as you are doing.

Upvotes: 1

Are you running this in a console app or "in SharePoint"?

Could it be that the account running the code doesnt have read permissions in C:\?

Upvotes: 0

Related Questions