Как вы загружаете файл в библиотеку документов в sharepoint?

Как программно загрузить файл в библиотеку документов в sharepoint?

В настоящее время я делаю приложение для Windows с использованием C#, которое будет добавлять документы в список библиотек документов.

8 ответов

Решение

Вы можете загружать документы в библиотеки SharePoint, используя объектную модель или веб-сервисы 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();
    }
}

Если вы получите эту ошибку "Значение не попадает в ожидаемый диапазон" в этой строке:

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

используйте вместо этого, чтобы исправить ошибку:

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

Всегда используйте URl для получения списков или других, потому что они уникальны, имена не лучший способ;)

С новой библиотекой 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);
    }
    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");
            }
        } 
    } 
try
{
    //Variablen für die Verarbeitung
    string source_file = @"C:\temp\offer.pdf";
    string web_url = "https://stackru.sharepoint.com";
    string library_name = "Documents";
    string admin_name = "admin@stackru.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;
}

В качестве альтернативы веб-сервисам вы можете использовать вызов документа put из API-интерфейса FrontPage RPC. Это дает дополнительное преимущество, позволяя вам предоставлять метаданные (столбцы) в том же запросе, что и данные файла. Очевидным недостатком является то, что протокол немного более неясен (по сравнению с очень хорошо документированными веб-сервисами).

Справочное приложение, объясняющее использование Frontpage RPC, см. В проекте SharePad на CodePlex.

Я думаю, что использование приложения — самый безопасный способ, потому что использование имени пользователя и пароля вызвало у меня множество проблем.

  1. Зарегистрируйте приложение:

https://ВАШЕ_ИМЯ_ТЕНАНТА.sharepoint.com/sites/ВАШЕ_ИМЯ_САЙТА/_layouts/15/AppRegNew.aspx

  1. Предоставить разрешение:

https://ВАШЕ_ИМЯ_ТЕНАТА.sharepoint.com/sites/ВАШЕ_ИМЯ_САЙТА/_layouts/15/appinv.aspx

Скопируйте ClientID и ClientSecret и сохраните их в файл App.config.

      <appSettings>
  <add key="ClientId" value="YOUR_CLIENT_ID" />
  <add key="ClientSecret" value="YOUR_CLIENT_SECRET" />
</appSettings>

Подробные инструкции: https://www.sharepointdiary.com/2019/03/connect-pnponline-with-appid-and-appsecret.html .

Вам понадобится этот пакет nuget:

Установочный пакет AppForSharePointOnlineWebToolkit — версия 3.1.5

Если при использовании пакета nuget у вас возникли какие-либо ошибки, установите библиотеку из сообщения об ошибке. Вероятно, есть лучший способ, чем использование этого пакета, но я получил именно его.

          static void Main(string[] args)
    {
        const string siteUrl = "https://YOUR_TENANT_NAME.sharepoint.com/sites/YOUR_SITE_NAME";
        var localFilePath = @"C:\your_file.txt";
        var libraryName = "Documents";
        UploadFileToSharePoint(siteUrl, localFilePath, libraryName);
    }

    private static void UploadFileToSharePoint(string siteUrl, string localFilePath, string libraryName)
    {
        var realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));

        //Get the access token for the URL.  
        var accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
        
        //Create a client context object based on the retrieved access token
        using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken))
        {
            var fci = new FileCreationInformation
            {
                Overwrite = true,
                Content = System.IO.File.ReadAllBytes(localFilePath),
                Url = Path.GetFileName(localFilePath)
            };
            
            var library = ctx.Web.Lists.GetByTitle(libraryName);
            var uploadFile = library.RootFolder.Files.Add(fci);
            
            ctx.Load(uploadFile);
            ctx.ExecuteQuery();
        }
    }

Я использовал эту статью, чтобы разрешить C# доступ к сайту sharepoint.

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

В основном вы создаете ключи ClientId и ClientSecret для доступа к сайту с помощью C#.

Надеюсь, это поможет вам!

Другие вопросы по тегам