kempyyyy
kempyyyy

Reputation: 224

How to upload a file in Sharepoint 2010 using c# console

Is there a way to automatically upload a file in Sharepoint 2010 using c#? We have no administrative control on the Sharepoint server. We just need to write a program that will upload a local file to a designated sharepoint library. The program will run on our server which in no way affiliated with the sharepoint server.

Upvotes: 3

Views: 3176

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59338

The following options could be considered for uploading the file into SharePoint via CSOM.

Prerequisites: SharePoint Foundation 2010 Client Object Model Redistributable

Using FileCollection.Add method

FileCollection.Add method adds a file to the collection based on provided file creation information

public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
{
    var fileCreationInfo = new FileCreationInformation
    {
        Content = System.IO.File.ReadAllBytes(uploadFilePath),
        Overwrite = true,
        Url = Path.GetFileName(uploadFilePath)
    };
    var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
    var uploadFile = targetFolder.Files.Add(fileCreationInfo);
    context.Load(uploadFile);
    context.ExecuteQuery();
}

Usage

using (var ctx = new ClientContext(webUri))
{
     ctx.Credentials = credentials;
     UploadFile(ctx,"Documents/Orders",@"c:\upload\user guide.docx");
}

where Orders is a folder in Documents library

According to Uploading files using Client Object Model in SharePoint 2010:

The above code might fail throwing a (400) Bad Request error depending on the file size.

Using File.SaveBinaryDirect method

File.SaveBinaryDirect method - uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.

public static void UploadFile(ClientContext context, string folderUrl, string uploadFilePath)
{
    using (var fs = new FileStream(uploadFilePath, FileMode.Open))
    {
        var fileName = Path.GetFileName(uploadFilePath);
        var fileUrl = String.Format("{0}/{1}", folderUrl, fileName);
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
    }
}

Usage

using (var ctx = new ClientContext(webUri))
{
     ctx.Credentials = credentials;
     UploadFile(ctx,"/News/Documents/Orders",@"c:\upload\user guide.docx");
}

where Orders is a folder in Documents library located on web site News.

FolderUrl format: /<web url>/<list url>/<folder url>

Upvotes: 3

Related Questions