2009-01-22 12 views

Respuesta

58

Puede subir documentos a las bibliotecas de SharePoint utilizando el Modelo de objetos o SharePoint Webservices.

Subir Modelo usando Objeto:

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(); 
    } 
} 
+2

Chadworthington, SPSite es parte de Microsoft.SharePoint espacio de nombres, por lo que es necesario agregar referencia a Microsoft.SharePoint.dll. Suponiendo que está desarrollando en el servidor, el archivo DLL se puede encontrar aquí: C: \ Archivos de programa \ Archivos comunes \ Microsoft Shared \ web server extensions \ 12 \ ISAPI \ Microsoft.SharePoint.dll –

+1

Espere un momento ... este código solo funcionará en una caja unida a la granja, ¿correcto? En cualquier otro cuadro, debe usar http://msdn.microsoft.com/en-us/library/ee857094.aspx – Ariel

+0

@Ariel. Tiene razón. Las API del cliente son la forma de acceder al servidor de SharePoint desde el exterior. También vea http://msdn.microsoft.com/en-us/library/ee537564.aspx –

5

Como alternativa a los servicios web, se puede utilizar el put document llamada de la API RPC FrontPage. Esto tiene el beneficio adicional de permitirle proporcionar metadatos (columnas) en la misma solicitud que los datos del archivo. El inconveniente obvio es que el protocolo es un poco más oscuro (en comparación con los servicios web muy bien documentados).

Para una aplicación de referencia que explique el uso de Frontpage RPC, consulte el proyecto SharePad en CodePlex.

7
string filePath = @"C:\styles\MyStyles.css"; 
    string siteURL = "http://MyDomain.net/"; 
    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

+1 para declaraciones CheckIn if. Considere no actualizar myLibrary. Puede causar conflictos de concurrencia. –

11

si obtiene este error "Valor no está dentro del rango esperado" en esta línea:

SPFolder myLibrary = oWeb.Folders[documentLibraryName]; 

usar en su lugar esto para fijar el error:

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

Use siempre URl para obtener listas u otras porque son únicas, los nombres no son la mejor manera;)

3

Con SharePoint 2013 nueva biblioteca, he conseguido hacer algo como esto:

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); 
    } 
+0

Hola, estoy obteniendo el error debajo. System.NotSupportedException: el formato de ruta ' no es compatible. en System.IO.FileStream.Init (ruta de cadena, modo FileMode, acceso a FileAccess, derechos Int32, boolean useRights, recurso compartido FileShare, Int32 bufferSize, opciones de FileOptions, SECATEMENT_ATTRIBUTES secAttrs, String msgPath, boolean bFromProxy, Boolean useLongPath, Boolean checkHost) ¿me pueden ayudar? – User5590

+0

¿Qué fila le da esta excepción? –

Cuestiones relacionadas