0

I have the following problem, I want to download a .xlsx file from a certain link using C#.

The link that I'm working with looks somewhat like this: "https://xxxxx/run?app=prc/prcStart.jsp&cmd=show&project_id=PRCPROJECT102151491224824986". and when I enter this link in my browser it automatically downloads a .xlsx file to my downloads folder.

What do I need to do to write a C# program that downloads this file from a link that automatically starts a download once entered? I don't really know where to start from here.

lee-m
  • 2,269
  • 17
  • 29
Moritz
  • 1
  • 1
  • 1
  • Similar question is answered here: https://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c – Caveman74 Aug 24 '22 at 10:34
  • 4
    Does this answer your question? [How to download a file from a URL in C#?](https://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c) – Caveman74 Aug 24 '22 at 10:36
  • So the top answer doesn't work for me because it requires me to specify the file name, I don't know the file name though, all I have is the link that automatically starts the download. The second answer doesn't work either, it only creates a 0kb xlsx file. – Moritz Aug 24 '22 at 11:12

1 Answers1

1

You can use HttpClient to handle issuing requests to remote servers, you'll then need to handle the response to save the content to a file somewhere.

In its simplest form that would look something like this:

using(var client = new HttpClient())
{
    var response = await client.GetByteArrayAsync("http://some-address");
    File.WriteAllBytes("Downloadedfile.xlsx", response);
}

This creates a new HttpClient instance, issues a GET request to a URL and returns back the request content as a byte[] (since xlsx files are a renamed .zip). Once you have that downloaded file content, you can save it to a file.

If you want to save the file specifically to the Downloads folder, that is a bit tricky since there appears to be no built-in way of achieving this purely from .NET managed code. See this answer for an example of falling back to the Win32 API to get this information.

lee-m
  • 2,269
  • 17
  • 29
  • Thank you for your answer, so this does create a .xlsx file for me but I cannot open it because it is corrupted, I tried to open it via text editor and it contains a weird text so I'm not sure if the conversion works correctly. – Moritz Aug 24 '22 at 12:11
  • The first thing I'd check is the length of the file matches with one you downloaded via a browser from the same URL. – lee-m Aug 24 '22 at 12:16