Search code examples
c#asp.net-mvcdownloadwebclient

C# read content of a file accessed via url into byte-array


my company is working with an Excel-file (xlsx) on Sharepoint. For my application I need the content of the file as a byte array.

When located on my local machine, I would use System.IO.File.ReadAllBytes(path).

How can I do the same with a file hosted on a server? The url is something like "https://sharepoint.com/excel.xlsx"

I tried new WebClient().DownloadData(url) but this returns something different I can't use. I think it returns the byte array of the file itself and not the content of the file.

Any ideas?


Solution

  • Rather than WebClient, try HttpClient:

    using (var client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync("https://sharepoint.com/excel.xlsx"))
    {
        byte[] fileContents = await response.Content.ReadAsByteArrayAsync();
    }