如果有可能,我想帮助我完成这项任务。我希望能够将文件上传到Sharepoint Online上的文件夹。目前,我只能上传到图书馆。以下是我目前使用的代码。
private void BtnUpload_Click(object sender, EventArgs e)
{
siteURL += "/" + tbDept.Text;
try
{
using (ClientContext ctx = new ClientContext(siteURL))
{
SecureString passWord = new SecureString();
foreach (var c in logUser.getPassword())
{
passWord.AppendChar(c);
}
ctx.Credentials = new SharePointOnlineCredentials(logUser.getUsername(), passWord);
Web web = ctx.Web;
foreach (string fname in arrAllFiles) //arrAllFiles --> contains multiple files to be uploaded
{
FileCreationInformation newFile = new FileCreationInformation();
newFile.Overwrite = true;
newFile.Content = System.IO.File.ReadAllBytes(fname);
newFile.Url = System.IO.Path.GetFileName(fname);
List docs = web.Lists.GetByTitle(tbLibrary.Text); //tbLibrary --> Library's Name
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
ctx.ExecuteQuery();
}
MessageBox.Show("Upload Complete!");
siteURL = "https://mycompany.sharepoint.com";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
siteURL = "https://mycompany.sharepoint.com";
}
}
代码运行正常。我只需要添加功能,以便将文件上传到库中的特定文件夹。
提前谢谢。
答案 0 :(得分:0)
这是我之前写过的一些示例代码。您可以根据自己的需要进行调整。 SaveBinaryDirect方法获取上下文和包含该文件夹的相对路径。这应该有用。
ClientContext ctx = new ClientContext("http://sp13");
Folder folder = ctx.Web.GetFolderByServerRelativeUrl("Shared Documents");
string file = String.Concat(Environment.CurrentDirectory, @"\Files\SharePointGuidance2010.pdf");
List docLib = ctx.Web.Lists.GetByTitle("Documents");
ctx.Load(docLib);
ctx.ExecuteQuery();
using (MemoryStream stream = new MemoryStream( System.IO.File.ReadAllBytes(file) ) )
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/shared documents/SubFolder/spg.pdf", stream, true);
}
或对您的代码进行以下编辑:
Folder folder = web.GetFolderByServerRelativeUrl("Documents/Subfolder");
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes(@”..\..\myfile.txt”);
fci.Url = “myfile.txt”;
fci.Overwrite = true;
File fileToUpload = folder.Files.Add(fci);
ctx.Load(fileToUpload);
ctx.ExecuteQuery();
答案 1 :(得分:0)
<强>更新强> 下面的代码工作,我自己测试了它:
var filePath = @"C:\PATH_TO_FILE\test.docx";
using (var context = new ClientContext("YOUR_SITE_URL") { Credentials = credentials })
{
var folder = context.Web.GetFolderByServerRelativeUrl("/sites/YOUR_SITE/LIBRARY_INTERNAL_NAME/FOLDER_NAME");
context.Load(folder);
context.ExecuteQuery();
folder.Files.Add(new FileCreationInformation
{
Overwrite = true,
Content = System.IO.File.ReadAllBytes(filePath),
Url = Path.GetFileName(filePath)
});
context.ExecuteQuery();
}