SharePoint 2010开发实例精选——通过客户端对象模型上传下载文件

为了使用ClientContext,我们需要添加两个dll引用到我们的项目中。Microsoft.SharePoint.Client.dll和Microsoft.SharePoint.Client.Runtime.dll。在本博文中,我们将学习如何:

  • 从SharePoint文档库中通过CAML获取ListItemCollection
  • 上载一个文档到SharePoint 文档库
  • 从SharePoint文档库下载一个文档

从SharePoint文档库中通过CAML获取ListItemCollection

我们可以像下面这样获取ListItemCollection:

ListItemCollection listItems = GetListItemCollectionFromSP("FileLeafRef", documentName, "Text", 1);

GetListItemCollectionFormSP方法可以用来获取列表项,其中第一个参数Name - 为FieldRef的名称,第二个参数value=FieldRef的值,第三个参数type - 是值的类型,最后一个参数rowLimit - 是返回最多多少条记录。

        private static ListItemCollection GetListItemCollectionFromSP(string name, string value, string type, int rowLimit)
        {
            ListItemCollection listItems = null;
            using (ClientContext clientContext = new ClientContext(siteURL))
            {
                List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
                CamlQuery camlQuery = new CamlQuery(); ;
                camlQuery.ViewXml =
                @"<View>
                <Query>
                <Where>
                <Eq>
                <FieldRef Name='" + name + @"'/>
                <Value Type='" + type + "'>" + value + @"</Value>
                </Eq>
                </Where>                    
                <RowLimit>" + rowLimit.ToString() + @"</RowLimit>
                </Query>
                </View>";
                listItems = documentsList.GetItems(camlQuery);
                clientContext.Load(documentsList);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
            }
            return listItems;
        }

上载一个文档到SharePoint 文档库

本例中我们需要上载文档到SharePoint文档库,同时更新该文档的元数据信息。比如通过ClientContext将一个说明字段设置为“核心内容”。代码如下:

        public static void UploadDocument(string siteURL, string documentListName,string documentListURL, string documentName, byte[] documentStream)
        {
            using (ClientContext clientContext = new ClientContext(siteURL))
            {
                //获取文档库
                List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
                var fileCreationInformation = new FileCreationInformation();
                //指定内容 byte[]数组,这里是 documentStream
                fileCreationInformation.Content = documentStream;
                //允许文档覆盖
                fileCreationInformation.Overwrite = true;
                //上载 URL地址
                fileCreationInformation.Url = siteURL + documentListURL + documentName;
                Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
                //更新元数据信息,这里是一个显示名为“描述”的字段,其字段名为“Description0”
                uploadFile.ListItemAllFields["Description0"] = "核心内容";
                uploadFile.ListItemAllFields.Update();
                clientContext.ExecuteQuery();
            }
        }

从SharePoint文档库下载一个文档

我们可以用如下代码下载一个文档

        public static Stream DownloadDocument(string siteURL, string documentName)
        {
            ListItem item = GetDocumentFromSP(documentName);
            if (item != null)
            {
                using (ClientContext clientContext = new ClientContext(siteURL))
                {
                    FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, item["FileRef"].ToString());
                    return fInfo.Stream;
                }
            }
            return null;
        }
        private static ListItem GetDocumentFromSP(string documentName)
        {
            //这个方法上面讨论过了,用于从SharePoint文档库获取列表项集合
            ListItemCollection listItems = GetListItemCollectionFromSP("FileLeafRef", documentName, "Text", 1);
            return (listItems != null && listItems.Count == 1) ? listItems[0] : null;
        }

调用示例:

        static string siteURL = "http://sp2010u/it";
        static string documentListName = "共享文档";

        static void Main(string[] args)
        {  
            UploadTest();
            DownloadTest();
            Console.ReadLine();
        }
        private static void DownloadTest()
        {
            string downloadDocumentName = "Lesson 2.pptx";
            Stream s = DownloadDocument(siteURL, downloadDocumentName);

            string saveTo = @"C:\" + downloadDocumentName;
            // 创建一个写入流
            FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.Write);
            // 写入到该流
            ReadWriteStream(s, writeStream);
            Console.WriteLine("下载完成!");
        }
        private static void UploadTest()
        {
            string uploadDocumentName = "Lesson 1.pptx";
            string openFrom =@"C:\"+uploadDocumentName;
            if (!System.IO.File.Exists(openFrom))
            {
                throw new ArgumentException(String.Format("{0} 不存在",openFrom), "openFrom");
            }

            FileStream fStream = System.IO.File.OpenRead(openFrom);
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            //上载到“共享文档”文档库下的“销售计划”文档集中
            UploadDocument(siteURL, documentListName, "/Shared%20Documents/%E9%94%80%E5%94%AE%E8%AE%A1%E5%88%92/", uploadDocumentName, contents);
            Console.WriteLine("上载完成!");
            fStream.Close(); 

        }
        // readStream 是你需要读取的流
        // writeStream 是你需要写入的流
        private static void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int Length = 256;
            Byte[] buffer = new Byte[Length];
            int bytesRead = readStream.Read(buffer, 0, Length);
            // 写入要求的字节
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, Length);
            }
            readStream.Close();
            writeStream.Close();
        }

上载到SharePoint中的效果如下:

希望对你有帮助!

 

参考资料

How to upload/download a document in SharePoint 2010 using Client Context Object Model

Microsoft.SharePoint.Client.ListItem Class

Microsoft.SharePoint.Client.File Class

Programmatically Upload document using Client object model – SharePoint 2010

posted @ 2010-08-24 12:00  Sunmoonfire  阅读(4617)  评论(3编辑  收藏  举报