首页 > 代码库 > 记一个使用Client Object Model上传文件的小例子

记一个使用Client Object Model上传文件的小例子

1. 新建一个C#的Console project.

2. 给project 添加reference:

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Runtime

3. 修改project的属性:

  • Platform target – x64
  • Target framework – .NET Framework 4

4. 修改代码如下:

 

using System;
using System.IO;
using System.Net;
using Microsoft.SharePoint.Client;

namespace ClientUploadTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext ctx = new ClientContext("http://mysp2013/sites/sc19/");
            ctx.Credentials = new NetworkCredential("administrator", "Password", "mydomain");

            using (FileStream fs = new FileStream(@"C:\temp\doc1.docx", FileMode.Open))
            {
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, 
                    @"/sites/sc19/site1/mydoclib/doc1.docx", 
                    fs, 
                    true);
            }

            Console.WriteLine("Uploaded File Successfully");
        }
    }
}

5. 运行成功.

 

后记

==================

一定要确保文件上传的目标地址的正确: URL正确, 文件夹的确存在.

否则会报HTTP 409 Conflict的.

 

为了避免HTTP 409, 你还需要注意我这个例子中使用的URL:

  • 构建ClientContext时, 用的是sitecollection的FULL URL.
  • 调用SaveBinaryDirect的时候, 用的是目标文件夹Full URL除去主机名加端口号后剩下的部分.

 

Happy Coding SharePoint!

 

参考资料

====================

Upload a document to a SharePoint list from Managed Client Side Object Model

http://pramodixit.wordpress.com/2013/07/23/upload-a-document-to-a-sharepoint-list-from-managed-client-side-object-model/ 

ClientContext error 409! HELP!

http://go4answers.webhost4life.com/Example/clientcontext-error-409-help-90813.aspx