使用C#到Sharepoint的附件

时间:2014-01-30 19:50:01

标签: c# sharepoint

我一直在尝试将新list items with attachments添加到我的列表中。 列表项添加正常,但我无法弄清楚如何将文件附加到这些项

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication3.TestReference;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            MVSDataContext dc = new MVSDataContext(
                new Uri("https:xxx_vti_bin/ListData.svc"));
            dc.Credentials = System.Net.CredentialCache.DefaultCredentials;

            TestListItem newItem = new TestListItem { Title = "test6" };
            dc.AddToTestList(newItem);
            dc.SaveChanges();

            /* up to this point everything works fine and i am able to add a new list item */                 

            FileStream fStream = File.OpenRead("C:\\xxxxx.xlsx");
            string fileName = fStream.Name.Substring(3);
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            fStream.Close();

            /* the file read  successfuly . Now I should use `contents` to upload the file */ 

            newItem.Attachments.Add(fStream.Name, contents); /* This line does not compile */


            dc.SaveChanges();

            }
        }
    }
}

我也尝试过来自here

DirectoryInfo  attachmentDirectory = new DirectoryInfo(@"C:\xxx");
            FileInfo[] attachments = attachmentDirectory.GetFiles();
            foreach (FileInfo attachment in attachments)
            {
                FileStream fs = new FileStream(attachment.FullName, FileMode.Open, FileAccess.Read);

                // Create a byte array of file stream length
                byte[] ImageData = new byte[fs.Length];

                //Read block of bytes from stream into the byte array
                fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

                //Close the File Stream
                fs.Close();

                newItem.Attachments.Add(attachment.Name, ImageData); 


            }

然而得到了同样的错误

如何附加列表项?


这是TestListItem类

      //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated by a tool.
    //     Runtime Version:4.0.30319.18052
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------

    // Original file name:
    // Generation date: 1/30/2014 11:00:30 AM
    namespace ConsoleApplication3.TestReference
    {

        /// <summary>
        /// There are no comments for MVSDataContext in the schema.
        /// </summary>
        public partial

 class MVSDataContext : global::System.Data.Services.Client.DataServiceContext
    {
        /// <summary>
        /// Initialize a new MVSDataContext object.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public MVSDataContext(global::System.Uri serviceRoot) : 
                base(serviceRoot)
        {
            this.ResolveName = new global::System.Func<global::System.Type, string>(this.ResolveNameFromType);
            this.ResolveType = new global::System.Func<string, global::System.Type>(this.ResolveTypeFromName);
            this.OnContextCreated();
        }
        partial void OnContextCreated();
        /// <summary>
        /// Since the namespace configured for this service reference
        /// in Visual Studio is different from the one indicated in the
        /// server schema, use type-mappers to map between the two.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        protected global::System.Type ResolveTypeFromName(string typeName)
        {
            if (typeName.StartsWith("Microsoft.SharePoint.DataService", global::System.StringComparison.Ordinal))
            {
                return this.GetType().Assembly.GetType(string.Concat("ConsoleApplication3.TestReference", typeName.Substring(32)), false);
            }
            return null;
        }
        /// <summary>
        /// Since the namespace configured for this service reference
        /// in Visual Studio is different from the one indicated in the
        /// server schema, use type-mappers to map between the two.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        protected string ResolveNameFromType(global::System.Type clientType)
        {
            if (clientType.Namespace.Equals("ConsoleApplication3.TestReference", global::System.StringComparison.Ordinal))
            {
                return string.Concat("Microsoft.SharePoint.DataService.", clientType.Name);
            }
            return null;
        }
        /// <summary>
        /// There are no comments for Attachments in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<AttachmentsItem> Attachments
        {
            get
            {
                if ((this._Attachments == null))
                {
                    this._Attachments = base.CreateQuery<AttachmentsItem>("Attachments");
                }
                return this._Attachments;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<AttachmentsItem> _Attachments;
        /// <summary>
        /// There are no comments for MasterPageGallery in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryItem> MasterPageGallery
        {
            get
            {
                if ((this._MasterPageGallery == null))
                {
                    this._MasterPageGallery = base.CreateQuery<MasterPageGalleryItem>("MasterPageGallery");
                }
                return this._MasterPageGallery;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryItem> _MasterPageGallery;
        /// <summary>
        /// There are no comments for MasterPageGalleryCompatibleUIVersionS in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryCompatibleUIVersionSValue> MasterPageGalleryCompatibleUIVersionS
        {
            get
            {
                if ((this._MasterPageGalleryCompatibleUIVersionS == null))
                {
                    this._MasterPageGalleryCompatibleUIVersionS = base.CreateQuery<MasterPageGalleryCompatibleUIVersionSValue>("MasterPageGalleryCompatibleUIVersionS");
                }
                return this._MasterPageGalleryCompatibleUIVersionS;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryCompatibleUIVersionSValue> _MasterPageGalleryCompatibleUIVersionS;
        /// <summary>
        /// There are no comments for TestList in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<TestListItem> TestList
        {
            get
            {
                if ((this._TestList == null))
                {
                    this._TestList = base.CreateQuery<TestListItem>("TestList");
                }
                return this._TestList;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<TestListItem> _TestList;
        /// <summary>
        /// There are no comments for UserInformationList in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<UserInformationListItem> UserInformationList
        {
            get
            {
                if ((this._UserInformationList == null))
                {
                    this._UserInformationList = base.CreateQuery<UserInformationListItem>("UserInformationList");
                }
                return this._UserInformationList;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<UserInformationListItem> _UserInformationList;
        /// <summary>
        /// There are no comments for Attachments in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToAttachments(AttachmentsItem attachmentsItem)
        {
            base.AddObject("Attachments", attachmentsItem);
        }
        /// <summary>
        /// There are no comments for MasterPageGallery in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToMasterPageGallery(MasterPageGalleryItem masterPageGalleryItem)
        {
            base.AddObject("MasterPageGallery", masterPageGalleryItem);
        }
        /// <summary>
        /// There are no comments for MasterPageGalleryCompatibleUIVersionS in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToMasterPageGalleryCompatibleUIVersionS(MasterPageGalleryCompatibleUIVersionSValue masterPageGalleryCompatibleUIVersionSValue)
        {
            base.AddObject("MasterPageGalleryCompatibleUIVersionS", masterPageGalleryCompatibleUIVersionSValue);
        }
        /// <summary>
        /// There are no comments for TestList in the schema.
        /// </summary>
..............

3 个答案:

答案 0 :(得分:2)

你有TestListItem的代码吗?看起来非常清楚,Add需要传递2个参数。

您需要为要添加的文件添加字节流 - 请参阅here

    foreach (FileInfo attachment in attachments)
    {
        FileStream fs = new FileStream(attachment.FullName , FileMode.Open,FileAccess.Read);

        // Create a byte array of file stream length
        byte[] ImageData = new byte[fs.Length];

        //Read block of bytes from stream into the byte array
        fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

        //Close the File Stream
        fs.Close();

        item.Attachments.Add(attachment.Name, ImageData); 


    }

答案 1 :(得分:1)

调用方法AddQueryOption而不是Add:

        newItem.Attachments.Add(fStream.Name, contents); /* This line does not compile */

        newItem.Attachments.AddQueryOption(fStream.Name, contents); /* This line does compile */

答案 2 :(得分:1)

希望这对其他用户有帮助。

这里的问题是SharePoint客户端对象模型没有在Attachments文件夹下创建项目的子文件夹。

要解决此问题,您应该通过添加Web服务参考来使用"/_vti_bin/lists.asmx" Web服务,如果需要指示,请遵循this link。 使用FR.WssODataCore.ListsWebService; 将参考添加到服务后,您可以使用以下代码段:

var listsServiceClient = new Lists
{
    Credentials = defaultContext.Credentials,
    Url = siteCollectionUrl + "/_vti_bin/lists.asmx"
};
listsServiceClient.AddAttachment(currentListName, listItemId, fileName, fileContent);

siteCollectionUrl是您服务的网址,如http://yourSite.ext/webName,而defaultContextMicrosoft.SharePoint.Client的实例,我曾用它来完成其他操作。

请注意,您需要引用包含Lists对象的Web服务引用

using MyServiceNameSpace.ListsWebService;

通过这种方式,我可以通过组合操作来使用ListData.svcLists.asmx端点,而仅使用.asmx服务上载附件。

Here的另一个好资源。