简体   繁体   English

SharePoint 2007:如何以编程方式将二进制文件上传到文档库?

[英]SharePoint 2007 : How to programmatically upload binary file into Document Library?

I encounter a problem to programmatically create an item into Document Library in SharePoint 2007. 我在以编程方式在SharePoint 2007中的文档库中创建项目时遇到问题。

Below is my code fragment, perhaps you might able to point out what is my error: 下面是我的代码片段,也许您可​​以指出我的错误是什么:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(_url))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList customList = web.Lists["Test1"];
            foreach (SPListItem ltItem in customList.Items)
            {
                if (ltItem.Attachments != null && ltItem.Attachments.Count > 0)
                {
                    //Get Test1 File Collection
                    SPFolder folder = web.GetFolder(ltItem.Attachments.UrlPrefix);
                    SPFileCollection fileColl = folder.Files;

                    //Get binary data of attachment
                    SPFile file = ltItem.ParentList.ParentWeb.GetFile(ltItem.Attachments.UrlPrefix + ltItem.Attachments[0]);
                    byte[] fileData = file.OpenBinary();

                    //Get Relative URL of attachment destination
                    string destFile = fileColl.Folder.Url + "/" + file.Name;

                    web.AllowUnsafeUpdates = true;
                    //Add attachment into Document Library
                    SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test2"];
                    SPFile file2 = docLib.RootFolder.Files.Add(destFile, fileData, true);
                    file2.Item.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
    }
});

I hit "Object reference not set to an instance of an object" at this link of code file2.Item.Update(); 我在代码file2.Item.Update()的此链接中单击了“对象引用未设置为对象的实例”;

Thank you in advanced. 在此先感谢您。

Why do you set the destFile like that? 为什么要这样设置destFile? The name of the attachment is enough.. 附件的名称就足够了。

string destFile = file.Name;

It's only necessary to append the relative URL of the attachement if your requirements say that you need folders, but then you'd create the folders before adding a file to it. 仅在您的要求说您需要文件夹时才需要附加附件的相对URL,但是您需要先创建文件夹,然后再向其中添加文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM