Reputation:
I have a simple console application that upload a file from a local folder to a library in sharepoint, and also have a method that download that folder, but using the url that is activated manually in the web site. But I need to download the same file that I upload a second later, it is for a test, AND WHAT I NEED IS TO ACTIVATE THE "VIEW LINK" FOR DOWNLOAD LATER. Here is my upload method:
static void o365SaveBinaryDirect(ClientContext o365Context, string o365LibraryName, string o365FilePath, string o365FileName) {
Web o365Web = o365Context.Web;
if (!LibraryExist(o365Context, o365Web, o365LibraryName)) {
CreateLibrary(o365Context, o365Web, o365LibraryName);
}
using (FileStream o365FileStream = new FileStream(o365FilePath, FileMode.Open)) {
Microsoft.SharePoint.Client.File.SaveBinaryDirect(o365Context, string.Format("/{0}/{1}", o365LibraryName, o365FileName), o365FileStream, true);
}
}
Now I have this method that download:
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl) {
using (var client = new WebClient()) {
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
I need to generate the url for download the file later.
Upvotes: 1
Views: 4599
Reputation: 59318
Some suggestions:
Microsoft.SharePoint.Client.File.SaveBinaryDirect
method from CSOM
API is used for uploafding a file, consider to utilize Microsoft.SharePoint.Client.File.OpenBinaryDirect
method for downloading a fileThe following example demonstrates how to upload a file into a library and then downloading it:
var sourceFilePath = @"c:\in\UserGuide.pdf"; //local file path;
var listTitle = "Documents"; //target library;
var list = ctx.Web.Lists.GetByTitle(listTitle);
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();
var targetFileUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, Path.GetFileName(sourceFilePath));
//upload a file
using (var fs = new FileStream(sourceFilePath, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fs, true);
}
//download a file
var downloadPath = @"c:\out\";
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, targetFileUrl);
var fileName = Path.Combine(downloadPath, Path.GetFileName(targetFileUrl));
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
Upvotes: 2