14

クライアント オブジェクト モデルを使用して新しい ListItems を追加する SharePoint リストがあります。ListItems の追加は問題ではなく、うまく機能します。

次に、添付ファイルを追加します。

次の方法で SaveBinaryDirect を使用しています。

File.SaveBinaryDirect(clientCtx, url.AbsolutePath + "/Attachments/31/" + fileName, inputStream, true);

添付ファイルを追加しようとしているアイテムに、クライアント オブジェクト モデルを使用せずに SharePoint サイトから追加された添付ファイルが既にある限り、問題なく動作します。

まだ添付ファイルがないアイテムに添付ファイルを追加しようとすると、次のエラーが発生します (両方とも発生しますが、同じファイルでは発生しませんが、これら 2 つのメッセージは一貫して表示されます)。

リモート サーバーがエラーを返しました: (409) 競合
リモート サーバーがエラーを返しました: (404) Not Found

このアイテムの添付ファイル フォルダーを最初に作成する必要があるのではないかと考えました。次のコードを試すと:

clientCtx.Load(ticketList.RootFolder.Folders);
clientCtx.ExecuteQuery();
clientCtx.Load(ticketList.RootFolder.Folders[1]);             // 1 -> Attachment folder
clientCtx.Load(ticketList.RootFolder.Folders[1].Folders);
clientCtx.ExecuteQuery();
Folder folder = ticketList.RootFolder.Folders[1].Folders.Add("33");
clientCtx.ExecuteQuery();

次のようなエラー メッセージが表示されます。

フォルダー「Lists/Ticket System/Attachment/33」を作成できません

SharePoint サイト/リストの完全な管理者権限を持っています。

私が間違っている可能性のあるアイデアはありますか?

ありがとう、ソーベン

4

6 に答える 6

12

私もこの問題に長い間悩まされていたので、リスト アイテムを正常に作成して添付ファイルを追加する方法を示す完全なコード サンプルを投稿しようと思いました。

クライアント オブジェクト API を使用してリスト アイテムを作成し、SOAP Web サービスを使用して添付ファイルを追加しています。これは、Web 上の他の場所で説明されているように、クライアント オブジェクト API は、アイテムのアップロード ディレクトリが既に存在するアイテムに添付ファイルを追加するためにのみ使用できるためです (たとえば、アイテムに既に添付ファイルがある場合)。そうしないと、409 エラーか何かで失敗します。ただし、SOAP Web サービスはこの問題に対処します。

私が克服しなければならなかったもう 1 つのことは、次の URL を使用して SOAP 参照を追加したにもかかわらず、次のことであることに注意してください。

https://my.sharepoint.installation/personal/test/_vti_bin/lists.asmx

VS が実際に app.config に追加した URL は次のとおりです。

https://my.sharepoint.installation/_vti_bin/lists.asmx

app.config を手動で正しい URL に戻す必要がありました。そうしないと、次のエラーが発生します。

リストが存在しません。選択したページには、存在しないリストが含まれています。別のユーザーによって削除された可能性があります。0x82000006

コードは次のとおりです。

    void CreateWithAttachment()
    {
        const string listName = "MyListName";
        // set up our credentials
        var credentials = new NetworkCredential("username", "password", "domain");

        // create a soap client
        var soapClient = new ListsService.Lists();
        soapClient.Credentials = credentials;

        // create a client context
        var clientContext = new Microsoft.SharePoint.Client.ClientContext("https://my.sharepoint.installation/personal/test");
        clientContext.Credentials = credentials;

        // create a list item
        var list = clientContext.Web.Lists.GetByTitle(listName);
        var itemCreateInfo = new ListItemCreationInformation();
        var newItem = list.AddItem(itemCreateInfo);

        // set its properties
        newItem["Title"] = "Created from Client API";
        newItem["Status"] = "New";
        newItem["_Comments"] = "here are some comments!!";

        // commit it
        newItem.Update();
        clientContext.ExecuteQuery();

        // load back the created item so its ID field is available for use below
        clientContext.Load(newItem);
        clientContext.ExecuteQuery();

        // use the soap client to add the attachment
        const string path = @"c:\temp\test.txt";
        soapClient.AddAttachment(listName, newItem["ID"].ToString(), Path.GetFileName(path),
                                  System.IO.File.ReadAllBytes(path));
    }

これが誰かに役立つことを願っています。

于 2012-07-27T09:45:53.477 に答える
9

この質問についてはマイクロソフトと話し合っています。添付ファイルをリモートで作成する唯一の方法は、List.asmx Web サービスのようです。このサブフォルダーも作成しようとしましたが、成功しませんでした。

于 2010-06-17T16:05:26.347 に答える
4

問題の認識と解決方法に関する有用な提案を前に出さなかったことは、Microsoft SharePoint チームにかなり悪い影響を与えています。これが私がそれに対処した方法です:

製品に同梱されている新しい SharePoint 2010 マネージ クライアントを使用しています。したがって、資格情報を含む SharePoint ClientContext が既にあります。次の関数は、添付ファイルをリスト アイテムに追加します。

private void SharePoint2010AddAttachment(ClientContext ctx, 
                                     string listName, string itemId, 
                                     string fileName, byte[] fileContent)
{
    var listsSvc = new sp2010.Lists();
    listsSvc.Credentials = _sharePointCtx.Credentials;
    listsSvc.Url = _sharePointCtx.Web.Context.Url + "_vti_bin/Lists.asmx";
    listsSvc.AddAttachment(listName, itemId, fileName, fileContent);
}

上記のコードの唯一の前提条件は、プロジェクト (私は Visual Studio 2008 を使用) に、http:// の URL から作成された sp2010 と呼ばれる _web_reference_ を追加することです。/_vti_bin/Lists.asmx

ボンチャンス...

于 2011-05-16T20:29:08.333 に答える
0

CSOM(SharePoint Client Object Model)アプリケーションでこれを使用して試してみましたが、うまくいきました

using (ClientContext context = new ClientContext("http://spsite2010"))
                {

                    context.Credentials = new NetworkCredential("admin", "password");
                    Web oWeb = context.Web;
                    List list = context.Web.Lists.GetByTitle("Tasks");
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = "<View><Where><Eq><FieldRef Name = \"Title\"/><Value Type=\"String\">New Task Created</Value></Eq></Where></View>";
                    ListItemCollection listItems = list.GetItems(query);
                    context.Load(listItems);
                    context.ExecuteQuery();
                    FileStream oFileStream = new FileStream(@"C:\\sample.txt", FileMode.Open);
                    string attachmentpath = "/Lists/Tasks/Attachments/" + listItems[listItems.Count - 1].Id + "/sample.txt";
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, attachmentpath, oFileStream, true);
                }

注: アイテム フォルダが既に作成されている場合にのみ機能します

于 2012-11-16T07:29:31.777 に答える
0

HTML:

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />

コードビハインドのイベント:

protected void UploadMultipleFiles(object sender, EventArgs e)
{
    Common.UploadDocuments(Common.getContext(new Uri(Request.QueryString["SPHostUrl"]),
    Request.LogonUserIdentity), FileUpload1.PostedFiles, new CustomerRequirement(), 5);
}

public static List<string> UploadDocuments<T>(ClientContext ctx,IList<HttpPostedFile> selectedFiles, T reqObj, int itemID)
{
    List<Attachment> existingFiles = null;
    List<string> processedFiles = null;
    List<string> unProcessedFiles = null;
    ListItem item = null;
    FileStream sr = null;
    AttachmentCollection attachments = null;
    byte[] contents = null;
    try
    {
        existingFiles = new List<Attachment>();
        processedFiles = new List<string>();
        unProcessedFiles = new List<string>();
        //Get the existing item
        item = ctx.Web.Lists.GetByTitle(typeof(T).Name).GetItemById(itemID);
        //get the Existing attached attachments
        attachments = item.AttachmentFiles;
        ctx.Load(attachments);
        ctx.ExecuteQuery();
        //adding into the new List
        foreach (Attachment att in attachments)
            existingFiles.Add(att);
        //For each Files which user has selected
        foreach (HttpPostedFile postedFile in selectedFiles)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            //If selected file not exist in existing item attachment
            if (!existingFiles.Any(x => x.FileName == fileName))
            {
                //Added to Process List
                processedFiles.Add(postedFile.FileName);
            }
            else
                unProcessedFiles.Add(fileName);
        }
        //Foreach process item add it as an attachment
        foreach (string path in processedFiles)
        {
            sr = new FileStream(path, FileMode.Open);
            contents = new byte[sr.Length];
            sr.Read(contents, 0, (int)sr.Length);
            var attInfo = new AttachmentCreationInformation();
            attInfo.FileName = Path.GetFileName(path);
            attInfo.ContentStream = sr;
            item.AttachmentFiles.Add(attInfo);
            item.Update();
        }
        ctx.ExecuteQuery();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        existingFiles = null;
        processedFiles = null;
        item = null;
        sr = null;
        attachments = null;
        contents = null;
        ctx = null;

    }
    return unProcessedFiles;
}
于 2015-09-23T07:19:48.593 に答える