プログラムで SharePoint のドキュメント ライブラリにファイルをアップロードするにはどうすればよいですか?
私は現在、ドキュメント ライブラリ リストにドキュメントを追加する C# を使用して Windows アプリケーションを作成しています。
プログラムで SharePoint のドキュメント ライブラリにファイルをアップロードするにはどうすればよいですか?
私は現在、ドキュメント ライブラリ リストにドキュメントを追加する C# を使用して Windows アプリケーションを作成しています。
オブジェクト モデルまたは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();
}
}
この行に「値が期待される範囲内にありません」というエラーが表示された場合:
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
代わりにこれを使用してエラーを修正します。
SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;
リストなどは一意であるため、常に URl を使用して取得します。名前は最適な方法ではありません ;)
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");
}
}
}
Web サービスの代わりに、FrontPage RPC API からput document呼び出しを使用できます。これには、ファイル データと同じ要求でメタデータ (列) を提供できるという追加の利点があります。明らかな欠点は、(非常によく文書化された Web サービスと比較して) プロトコルが少しわかりにくいことです。
Frontpage RPC の使用方法を説明するリファレンス アプリケーションについては、CodePlex のSharePadプロジェクトを参照してください。