3

I am working on an ASP.NET Core web app and I'm using Razor Pages.

I have some URLs displayed in my app and when I click on one of them, I want to download the file corresponding to that URL on a folder on the server where the application is stored, not on the client.

This is important because the file needs to be processed server-side by some other third-party applications.

The URLs along with other metadata are coming from a database and I created a DB context to load them. I made a CSS HTML file and displayed the information in a form. When I click on a button, I post the URL to a method handler.

I receive the URL in the method but I don't know how to download that file on the server without downloading it first on the client and then saving/uploading it to the server. How can I achieve this?

Karma
  • 1
  • 1
  • 3
  • 9
Cosmos24Magic
  • 219
  • 4
  • 17
  • Post the code you have – Caius Jard Aug 07 '21 at 16:51
  • It's just an OnPost method that receives a url parameter. I don't know how to download the file from that url on the server instead of the client. I tried messing a bit with HttpWebRequest but I didn't manage to do what I wanted. – Cosmos24Magic Aug 07 '21 at 17:11
  • I'm sure SO is full of "how do I download a file in c#" posts you can give a go at. I'd ignore the "it's on a server" part to start with.. just get a console app download working then port the code – Caius Jard Aug 07 '21 at 17:13
  • the "it's on a server" part is the most important part..the app works fine if I'm using it on my local machine, but I plan on using it from my phone and I need to download the files on the server, not on my phone – Cosmos24Magic Aug 07 '21 at 17:59
  • Where did I tell you to download a file on your phone? What phone do you have that runs c#? – Caius Jard Aug 07 '21 at 19:09

2 Answers2

8

Starting .NET 6 WebRequest, WebClient, and ServicePoint classes are deprecated.

To download a file using the recommended HttpClient instead, you'd do something like this:

// using System.Net.Http;
// using System.IO;

var httpClient = new HttpClient();
var responseStream = await httpClient.GetStreamAsync(requestUrl);
using var fileStream = new FileStream(localFilePath, FileMode.Create);
responseStream.CopyTo(fileStream);

Remember to not use using, and to not dispose the HttpClient instance after every use. More context here and here.

The recommended way to acquire a HttpClient instance is to get it from IHttpClientFactory. If you get an HttpClient instance using a HttpClientFactory, you may dispose the HttpClient instance after every use.

galdin
  • 12,411
  • 7
  • 56
  • 71
3

can use System.Net.WebClient

using (WebClient Client = new WebClient ())
{
    Client.DownloadFile (
            // Param1 = Link of file
            new System.Uri("Given URL"),
            // Param2 = Path to save
            "On SERVER PATH"
        );
}