2012-03-24 1 views
21

Ich muss ein Dokument mithilfe des Client-seitigen Objektmodells von .NET (C#) in eine SharePoint-Liste oder einen Ordner hochladen. Was ist der beste Weg, dies zu tun?Ein Dokument aus dem Client-seitigen Objektmodell in eine SharePoint-Liste hochladen

Die Anforderungen sind wie folgt:

  • Set Metadatenwerte

  • Keine Beschränkung der Dateigröße

  • Muss mit Bibliotheken arbeiten, die die Listenansicht Threshold

überschreiten
+0

Fragen über das JavaScript CLIENT-SIDE-Modell oder den normalen Client-Modus l? –

+0

^Er erklärte, dass er die .NET (C#) CSOM verwendet. – BrainSlugs83

Antwort

19

Zum Hochladen des Dokuments in Sharepoin t Document Library verwenden folgende Funktion in Clientobjektmodell:

public void UploadDocument(string siteURL, string documentListName, 
string documentListURL, string documentName, 

byte[] documentStream) 
{ 

using (ClientContext clientContext = new ClientContext(siteURL)) 
{   

//Get Document List 
List documentsList = clientContext.Web.Lists.GetByTitle(documentListName); 

var fileCreationInformation = new FileCreationInformation(); 
//Assign to content byte[] i.e. documentStream 

fileCreationInformation.Content = documentStream; 
//Allow owerwrite of document 

fileCreationInformation.Overwrite = true; 
//Upload URL 

fileCreationInformation.Url = siteURL + documentListURL + documentName; 
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
    fileCreationInformation); 

//Update the metadata for a field having name "DocType" 
uploadFile.ListItemAllFields["DocType"] = "Favourites"; 

uploadFile.ListItemAllFields.Update(); 
clientContext.ExecuteQuery(); 

} 
} 

Der Link ist auch hilfreich für Sie 1) http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx

2) http://msdn.microsoft.com/en-us/library/ee956524.aspx

3) http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20

+0

Danke. Follow-up-Frage: Der erste Link erklärt, wie man das Upload-Limit ändert, aber es ist serverseitiger Code. Wissen Sie, wie Sie serverseitigen Code schreiben und bereitstellen? Können wir ein einfaches Skript schreiben und es auf dem Server ausführen? Gibt es eine andere Möglichkeit, das Limit zu ändern (Client-Seite vielleicht?)? –

+0

Leider können mit diesem Code keine Dateien mit mindestens 1,5 MB in SharePoint hochgeladen werden. Dazu müssen Sie die SaveBindaryDirect-Methode, REST oder FileCreationInformation.ContentStream verwenden. –

+0

Ich stelle fest, dass beim Hochladen einer Datei auf diese Weise bei aktivierter Versionierung bei jedem Update zwei separate Versionen angezeigt werden: einmal beim Hinzufügen einer Datei und beim Aufruf von ListItemAllFields.Update() – Kristopher

13

Ein anderer Weg ist Verwenden der SaveBinaryDirect-Methode. Die SaveBinaryDirect-Methode verwendet Web Based Distributed Authoring und Versioning (WebDAV) zum Hochladen und Herunterladen von Dateien. Ohne einen eigenen benutzerdefinierten WCF-Dienst zu erstellen, ist WebDAV die effizienteste Methode zum Hoch- und Herunterladen von Dateien.

using (FileStream fs = new FileStream(FileToImport, FileMode.OpenOrCreate)) 
{ 
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, uri.LocalPath, fs, true); 
} 
Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(uri.LocalPath); 
context.Load(newFile); 
context.ExecuteQuery(); 

//check out to make sure not to create multiple versions 
newFile.CheckOut(); 

ListItem item = newFile.ListItemAllFields; 
item["Created"] = info.SourceFile.CreationTime; 
item["Modified"] = info.SourceFile.LastWriteTime; 
item.Update(); 

// use OverwriteCheckIn type to make sure not to create multiple versions 
newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn); 
+1

Beim Einchecken der Datei wird das geänderte Feld aktualisiert zu dem Zeitpunkt, zu dem die Datei eingecheckt wurde, sodass Ihr Beispiel nicht wie erwartet funktioniert. – Eccentropy

7

Noch eine weitere Option, um eine Datei in einer Sharepoint-Website (einschließlich Sharepoint Online) für das Hochladen mit File.SaveBinaryDirect Method:

/// <summary> 
/// Uploads the specified file to a SharePoint site 
/// </summary> 
/// <param name="context">SharePoint Client Context</param> 
/// <param name="listTitle">List Title</param> 
/// <param name="fileName">File Name</param> 
private static void UploadFile(ClientContext context, string listTitle,string fileName) 
{ 
    using (var fs = new FileStream(fileName, FileMode.Open)) 
    { 
      var fi = new FileInfo(fileName); 
      var list = context.Web.Lists.GetByTitle(listTitle); 
      context.Load(list.RootFolder); 
      context.ExecuteQuery(); 
      var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name); 

      Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true); 
     } 
    } 
+1

Elegant .. danke! – Colbs

6

ich, dass der Anteil der Delax Post gefunden, die neue Datei aktualisiert Attribute/Spalten wird nicht Arbeit, hier ist eine andere Version, die sogar für eine benutzerdefinierte Infopath-Bibliothek mit beworbenem Feld woks:

public string AddNewForm(string WebUrl, string NewTitle) 
    { 
     string strMsg = ""; 
     if (string.IsNullOrEmpty(WebUrl)) 
      return EmptyProcURL; 

     try 
     { 
      // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. 
      using (ClientContext client = new ClientContext(WebUrl)) 
      { 
       //client.Credentials = System.Net.CredentialCache.DefaultCredentials; 

       // Assume that the web site has a library named "FormLibrary". 
       var formLib = client.Web.Lists.GetByTitle("FormLibrary"); 
       client.Load(formLib.RootFolder); 
       client.ExecuteQuery(); 

       // FormTemplate path, The path should be on the local machine/server ! 
       string fileName = @"D:\Projects\FormTemplate.xml"; 

       var fileUrl = ""; 

       //Craete FormTemplate and save in the library. 
       using (var fs = new FileStream(fileName, FileMode.Open)) 
       { 
        var fi = new FileInfo("newForm.xml"); 
        fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name); 
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true); 
       } 

       // Get library columns collection. 
       var libFields = formLib.Fields; 
       client.Load(libFields); 
       client.ExecuteQuery(); 

       Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl); 

       ListItem item = newFile.ListItemAllFields; 

       // Here the index of Title column is 9, you may use this format to update any column (even promoted fields). 
       // To find the index of interested column you should inspect libFields at debug mode, look in the libFields.Fields collection to find the index! 
       item[libFields[9].StaticName] = NewTitle ; 
       item.Update(); 
       client.ExecuteQuery(); 
      } 
     } 
     catch (Exception ex) 
     { 
      strMsg = ex.Message; 
     } 

     return strMsg; 
    } 
Verwandte Themen