51

プログラムで SharePoint のドキュメント ライブラリにファイルをアップロードするにはどうすればよいですか?

私は現在、ドキュメント ライブラリ リストにドキュメントを追加する C# を使用して Windows アプリケーションを作成しています。

4

7 に答える 7

72

オブジェクト モデルまたは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();
    }
}
于 2009-01-22T11:01:14.667 に答える
12

この行に「値が期待される範囲内にありません」というエラーが表示された場合:

SPFolder myLibrary = oWeb.Folders[documentLibraryName];

代わりにこれを使用してエラーを修正します。

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

リストなどは一意であるため、常に URl を使用して取得します。名前は最適な方法ではありません ;)

于 2012-12-05T15:34:05.387 に答える
6
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");
        }
    } 
} 
于 2012-10-10T15:58:17.157 に答える
5

Web サービスの代わりに、FrontPage RPC API からput document呼び出しを使用できます。これには、ファイル データと同じ要求でメタデータ (列) を提供できるという追加の利点があります。明らかな欠点は、(非常によく文書化された Web サービスと比較して) プロトコルが少しわかりにくいことです。

Frontpage RPC の使用方法を説明するリファレンス アプリケーションについては、CodePlex のSharePadプロジェクトを参照してください。

于 2009-01-22T19:25:35.677 に答える