【问题标题】:How do you upload a file to a document library in sharepoint?如何将文件上传到 sharepoint 中的文档库?
【发布时间】:2010-10-02 21:06:40
【问题描述】:

如何以编程方式将文件上传到 sharepoint 中的文档库?

我目前正在使用 C# 制作一个 Windows 应用程序,它会将文档添加到文档库列表中。

【问题讨论】:

    标签: c# sharepoint upload


    【解决方案1】:

    您可以使用对象模型或SharePoint Webservices 将文档上传到 SharePoint 库。

    使用对象模型上传:

    String fileToUpload = @"C:\YourFile.txt";
    String sharePointSite = "http://yoursite.com/sites/Research/";
    String documentLibraryName = "Shared Documents";
    
    using (SPSite oSite = new SPSite(sharePointSite))
    {
        using (SPWeb oWeb = oSite.OpenWeb())
        {
            if (!System.IO.File.Exists(fileToUpload))
                throw new FileNotFoundException("File not found.", fileToUpload);                    
    
            SPFolder myLibrary = oWeb.Folders[documentLibraryName];
    
            // Prepare to upload
            Boolean replaceExistingFiles = true;
            String fileName = System.IO.Path.GetFileName(fileToUpload);
            FileStream fileStream = File.OpenRead(fileToUpload);
    
            // Upload document
            SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
    
            // Commit 
            myLibrary.Update();
        }
    }
    

    【讨论】:

    • Chadworthington,SPSite 是 Microsoft.SharePoint 命名空间的一部分,因此您需要添加对 Microsoft.SharePoint.dll 的引用。假设您在服务器上开发,可以在此处找到 dll:C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.SharePoint.dll
    • 等一下……这个代码只能在加入农场的盒子里工作,对吗?在任何其他框中,它需要使用msdn.microsoft.com/en-us/library/ee857094.aspx
    • 你不需要调用 myLibrary.Update();在 Files.Add(..) 之后添加文件
    • 这对我来说效果很好,除了我在之后删除文件时必须在文件流上使用“使用”(以便删除工作)。我将其更改为: using (FileStream fileStream = File.OpenRead(fileToUpload)) { // 上传文档 SPFile spfile = doclib.Files.Add(fileName, fileStream, replaceExistingFiles); }
    • 这不是一个好的解决方案。它需要以同时是 DBO 和 SP Farm 管理员的身份运行,这对于上传文件的任务来说太荒谬了。
    【解决方案2】:

    如果您在此行中收到此错误“值不在预期范围内”:

    SPFolder myLibrary = oWeb.Folders[documentLibraryName];
    

    改用这个来修复错误:

    SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;
    

    总是使用 URl 来获取列表或其他,因为它们是唯一的,名称不是最好的方法;)

    【讨论】:

      【解决方案3】:

      使用 SharePoint 2013 新库,我设法做到了这样的事情:

      private void UploadToSharePoint(string p, out string newUrl)  //p is path to file to load
      {
          string siteUrl = "https://myCompany.sharepoint.com/site/";
          //Insert Credentials
          ClientContext context = new ClientContext(siteUrl);
      
          SecureString passWord = new SecureString();
          foreach (var c in "mypassword") passWord.AppendChar(c);
          context.Credentials = new SharePointOnlineCredentials("myUserName", passWord);
          Web site = context.Web;
      
          //Get the required RootFolder
          string barRootFolderRelativeUrl = "Shared Documents/foo/bar";
          Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);
      
          //Create new subFolder to load files into
          string newFolderName = baseName + DateTime.Now.ToString("yyyyMMddHHmm");
          barFolder.Folders.Add(newFolderName);
          barFolder.Update();
      
          //Add file to new Folder
          Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
          FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
          currentRunFolder.Files.Add(newFile);
          currentRunFolder.Update();
      
          context.ExecuteQuery();
      
          //Return the URL of the new uploaded file
          newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);
      }
      

      【讨论】:

      • 您好,我遇到了以下错误。 System.NotSupportedException:不支持给定路径的格式。在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 你能请帮忙?
      • 哪一行给出了这个例外?
      【解决方案4】:
      string filePath = @"C:\styles\MyStyles.css"; 
      string siteURL = "http://example.org/"; 
      string libraryName = "Style Library"; 
      
      using (SPSite oSite = new SPSite(siteURL)) 
      { 
          using (SPWeb oWeb = oSite.OpenWeb()) 
          { 
              if (!System.IO.File.Exists(filePath)) 
                  throw new FileNotFoundException("File not found.", filePath);                     
      
              SPFolder libFolder = oWeb.Folders[libraryName]; 
      
              // Prepare to upload 
              string fileName = System.IO.Path.GetFileName(filePath); 
              FileStream fileStream = File.OpenRead(filePath); 
      
              //Check the existing File out if the Library Requires CheckOut
              if (libFolder.RequiresCheckout)
              {
                  try {
                      SPFile fileOld = libFolder.Files[fileName];
                      fileOld.CheckOut();
                  } catch {}
              }
      
              // Upload document 
              SPFile spfile = libFolder.Files.Add(fileName, fileStream, true); 
      
              // Commit  
              myLibrary.Update(); 
      
              //Check the File in and Publish a Major Version
              if (libFolder.RequiresCheckout)
              {
                      spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
                      spFile.Publish("Publish Comment");
              }
          } 
      } 
      

      【讨论】:

      • +1 用于 CheckIn if 语句。考虑不更新 myLibrary。它可能会导致并发冲突。
      【解决方案5】:

      作为 Web 服务的替代方案,您可以使用来自 FrontPage RPC API 的 put document 调用。这具有使您能够在与文件数据相同的请求中提供元数据(列)的额外好处。明显的缺点是该协议有点晦涩(与有据可查的 Web 服务相比)。

      有关说明 Frontpage RPC 使用的参考应用程序,请参阅 CodePlex 上的 SharePad 项目。

      【讨论】:

        【解决方案6】:
        try
        {
            //Variablen für die Verarbeitung
            string source_file = @"C:\temp\offer.pdf";
            string web_url = "https://stackoverflow.sharepoint.com";
            string library_name = "Documents";
            string admin_name = "admin@stackoverflow.com";
            string admin_password = "Password";
        
            //Verbindung mit den Login-Daten herstellen
            var sercured_password = new SecureString();
            foreach (var c in admin_password) sercured_password.AppendChar(c);
            SharePointOnlineCredentials credent = new 
            SharePointOnlineCredentials(admin_name, sercured_password);
        
            //Context mit Credentials erstellen
            ClientContext context = new ClientContext(web_url);
            context.Credentials = credent;
        
            //Bibliothek festlegen
            var library = context.Web.Lists.GetByTitle(library_name);
        
            //Ausgewählte Datei laden
            FileStream fs = System.IO.File.OpenRead(source_file);
        
            //Dateinamen aus Pfad ermitteln
            string source_filename = Path.GetFileName(source_file);
        
            //Datei ins SharePoint-Verzeichnis hochladen
            FileCreationInformation fci = new FileCreationInformation();
            fci.Overwrite = true;
            fci.ContentStream = fs;
            fci.Url = source_filename;
            var file_upload = library.RootFolder.Files.Add(fci);
        
            //Ausführen
            context.Load(file_upload);
            context.ExecuteQuery();
            
            //Datenübertragen schließen
            fs.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Fehler");
            throw;
        }
        

        【讨论】:

        • add对你的回答做一些解释
        • 迄今为止最好的。
        【解决方案7】:

        我使用这篇文章允许 c# 访问一个共享点站点。

        http://www.thesharepointguide.com/access-office-365-using-a-console-application/

        基本上,您创建一个 ClientId 和 ClientSecret 密钥以使用 c# 访问该站点

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-08
          • 1970-01-01
          • 1970-01-01
          • 2011-08-25
          • 2010-10-01
          • 2013-12-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多