Download a specific file from SharePoint (CSOM) using C# - c#

I'm developing a C# based application that requires to download, checkout, upload, check in on a specific file from/to Sharepoint with CSOM. So I have two questions here:
Firstly, on download, is there others way to download a specific named file under folder "Document" instead of searching through GetItemByID(). Please refer to code below:
string siteUrl = #"http://test.com/sites/company/";
ClientContext ctx = new ClientContext(siteUrl);
ctx.Credentials = new NetworkCredential("username", "password" , "domain");
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
var list = ctx.Web.Lists.GetByTitle("Document");
var listItem = list.GetItemById();
ctx.Load(list);
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var fileName = Path.Combine("C:\\", (string)listItem.File.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
Secondly, in regards to the workflow (download, modify, check out, upload, check in), is this feasible of doing?
Thanks in advance.

For getting specific file, no need to get ListItem by Id, instead, directly pass server relativer url like this:
ClientContext clientContext = new ClientContext("http://sp/sites/dev");
Web web = clientContext.Web;
Microsoft.SharePoint.Client.File filetoDownload = web.GetFileByServerRelativeUrl("/sites/dev/shared%20documents/mytest.txt");
clientContext.Load(filetoDownload);
clientContext.ExecuteQuery();
var fileRef = filetoDownload.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
var fileName = Path.Combine("C:\\", (string)filetoDownload.Name);
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}
For other usage, checkout,update,checkin, I would suggest you can still use CSOM, as there are buit-in functions support:
File methods

Related

MemoryStream Uploading Empty File to SharePoint in C# MVC Project

I am testing out the ability to upload a file to SharePoint. I am using the following code:
var targetSiteURL = #"https://company.sharepoint.com/sites/ProjectRoom";
var login = "user#company.com";
var password = "PWD123!";
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
var ctx = new ClientContext(targetSiteURL)
{
Credentials = new SharePointOnlineCredentials(login, securePassword)
};
var fileName = vm.UploadedFile.FileName;
using (var target = new MemoryStream())
{
vm.UploadedFile.InputStream.CopyTo(target);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, $"/sites/ProjectRoom/Project Room Test/{fileName}", target, true);
}
A file is uploaded with the correct name to the correct location. However, the file is blank.
UploadedFile is a property in my ViewModel =>
public HttpPostedFileBase UploadedFile { get; set; }
I also have an input type of file named UploadedFile in my form, which I use to select the file to upload =>
<input type="file" name="UploadedFile" id="UploadedFile"/>
My question is: Why is the file that I upload blank?
A MemoryStream has an internal pointer to the next byte to read. After inserting bytes into it, you need to reset it back to the start or the consuming app may not realise and will read it as empty. To reset it, just set the Position property back to zero:
vm.UploadedFile.InputStream.CopyTo(target);
// Add this line:
target.Position = 0;
Microsoft.SharePoint.Client.File.SaveBinaryDirect(....);

Azure Data Lake Storage File Share File Path

I am not able to access any path in Azure file share folders. Everything I've tried is giving me an error "Operation: GETFILESTATUS failed with Unknown Error: Name or service not known Name or service not known Source". Does this code look okay?
var adlsClient = AdlsClient.CreateClient("myDataLakeAccount.azuredatalakestore.net", "Token");
using MemoryStream memoryStream = new MemoryStream();
using StreamWriter streamWriter = new StreamWriter(memoryStream);
streamWriter.WriteLine("Testing file content to insert.");
using var file = adlsClient.CreateFile("/Folder1/Folder2/Pending/TestFile.txt", IfExists.Overwrite);
byte[] textByteArray = memoryStream.ToArray();
file.Write(textByteArray, 0, textByteArray.Length);
I am using below snippet of code to add a file in ADLS Gen2 container. You can use the below :
var storageAccountName = <YourStorageAccountName>;
var storageAccountKey = <YourStorageAccountKey>;
string serviceUri = "https://" + storageAccountName + ".dfs.core.windows.net";
var sampleFilePath = <YourLocalFilePath>;
StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(storageAccountName, storageAccountKey);
// Create DataLakeServiceClient using StorageSharedKeyCredentials
DataLakeServiceClient serviceClient = new DataLakeServiceClient(new Uri(serviceUri), sharedKeyCredential);
// Get a reference to a filesystem named "sample-filesystem-append" and then create it
DataLakeFileSystemClient filesystem = serviceClient.GetFileSystemClient("folder1");
filesystem.CreateIfNotExists();
DataLakeDirectoryClient directory = filesystem.GetDirectoryClient("/folder2/pending/");
directory.CreateIfNotExists();
DataLakeFileClient file = directory.GetFileClient("test1.txt");
file.CreateIfNotExists();
var SampleFileContent = File.OpenRead(sampleFilePath);
file.Append(SampleFileContent, 0);
file.Flush(SampleFileContent.Length);
After executing the above code I could see the results in the ADLS Gen2 storage account
Date is written in the file
Refer here

Uploading Image into SharePoint document library C#

I have a web service that currently passes base64 image format, However, How can I insert it into a sharepoint library? should i convert it to bytes array ?
Yes, need to read image file stream and then use Microsoft.SharePoint.Client.File.SaveBinaryDirect to save into SharePoint library:
var fileName=#"C:\Test.jpg";
using (ClientContext context = new ClientContext("http://sp/"))
{
using (var fs = new FileStream(fileName, FileMode.Open))
{
var fi = new FileInfo(fileName);
var list = context.Web.Lists.GetByTitle("Documents");
context.Load(list.RootFolder);
context.ExecuteQuery();
var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}
Here is a similiar thread for your reference:
How to Upload Images to SharePoint Online(Office 365) Picture-library using CSOM (Java Script)?

Download all documents from SharePoint List using the URL

I wanted to know how to download all documents from a SharePoint list using the SharePoint client object model (CSOM) (Microsoft.SharePoint.Client) and the lists full URL.
For example, if the URL was http://teamhub.myorg.local/sites/teams/it/ISLibrary/Guides/
Is it possible to connect directly to that URL and retrieve all documents stored there?
I have tried out the below code but I am getting an error, also it seems to require that I split the URL into two parts.
string baseURL = "http://teamhub.myorg.local/sites/";
string listURL = "teams/it/ISLibrary/Guides/";
var ctx = new ClientContext(baseURL);
ctx.Credentials = new SharePointOnlineCredentials(userName, SecuredpassWord);
var list = ctx.Web.GetList(listURL);
ctx.Load(list);
ctx.ExecuteQuery();
Console.WriteLine(list.Title);
When I run this code I simply get a "File not found" error.
Can it be done by simply passing in the full url somewhere?
I will need to do this connection and get all documents 100's of times over for many different lists, so it would be best if there is a way to do it using the full URL.
Any advice is appreciated. Thanks
Microsoft.SharePoint.Client.Web.GetListByUrl use webRelativeUrl, for example:
My site: https://tenant.sharepoint.com/sites/TST, library: https://tenant.sharepoint.com/sites/TST/MyDoc4
So the code would be:
Web web = clientContext.Web;
var lib=web.GetListByUrl("/MyDoc4");
The listURL you shared seems a folder, so we could get the folder and files in folder as below:
Web web = clientContext.Web;
Folder folder = web.GetFolderByServerRelativeUrl("/sites/TST/MyDoc4/Folder");
var files = folder.Files;
clientContext.Load(files);
clientContext.ExecuteQuery();
Download fileļ¼š
foreach (var file in files)
{
clientContext.Load(file);
Console.WriteLine(file.Name);
ClientResult<Stream> stream = file.OpenBinaryStream();
clientContext.ExecuteQuery();
var fileOut = Path.Combine(localPath, file.Name);
if (!System.IO.File.Exists(fileOut))
{
using (Stream fileStream = new FileStream(fileOut, FileMode.Create))
{
CopyStream(stream.Value, fileStream);
}
}
}
private static void CopyStream(Stream src, Stream dest)
{
byte[] buf = new byte[8192];
for (; ; )
{
int numRead = src.Read(buf, 0, buf.Length);
if (numRead == 0)
break;
dest.Write(buf, 0, numRead);
}
}

How to get jpg file from CloudFiles on Rackspace using openstack.net

I'm running the below code in my controller in an asp.net mvc project. I want to enable the user to view or download the files that I store on Cloud Files on rackspace.
var identity =
new CloudIdentity()
{
Username = "username",
APIKey = "apikey"
};
var storage = new CloudFilesProvider(identity);
Stream jpgStream = new MemoryStream();
storage.GetObject("files.container", "1.jpg", jpgStream);
Stream pdfStream = new MemoryStream();
storage.GetObject("files.container", "2.pdf", pdfStream);
var jpgResult = File(jpgStream, "Image/jpg", "1.jpg");
var pdfResult = File(pdfStream, "Application/pdf", "2.pdf");
The above code works when I return pdfResult. I get the correct file. But when I return the jpgResult, the browser downloads 1.jpg as an empty 0KB file.
Am I doing this the right way? Any idea what the problem might be?
Problem solved after I added:
jpgStream.Position = 0;
pdfStream.Position = 0;
Before the File() call. As per the question: File is empty and I don't understand why. Asp.net mvc FileResult
I don't know why this wasn't an issue with the pdf file.
You can also use the GetObjectSaveToFile method.

Categories