ASP.NET Core Download File From URL/URI Using WebClient
This article uses ASP.NET Core. If using the older .NET Framework, see this article, though, not much has changed.
Using WebClient.DownloadFile()
is a very efficient way to download a file and save it somewhere to be processed. Notice that a cookie is being sent to the server.
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.Headers.Add("Cookie: Authentication=user"); // add a cookie header to the request
try
{
string filename = System.Guid.NewGuid().ToString("N"); // use global unique identifier for file name to avoid conflicts
wc.DownloadFile("http://www.prowaretech.com/", "C:\\files\\" + filename); // could add file extension here
// do something with file
}
catch (System.Exception ex)
{
// check exception object for the error
}
}
WebClient.DownloadString()
is a less efficient use of server memory.
using (System.Net.WebClient wc = new System.Net.WebClient())
{
try
{
string str = wc.DownloadString("http://www.prowaretech.com/");
// do something with str
}
catch (System.Exception ex)
{
// check exception object for the error
}
}
WebClient.DownloadData()
is another less efficient use of server memory. It downloads a file into a byte array.
using (System.Net.WebClient wc = new System.Net.WebClient())
{
try
{
byte[] data = wc.DownloadData("http://www.prowaretech.com/");
// do something with data
}
catch (System.Exception ex)
{
// check exception object for the error
}
}
WebClient.OpenRead()
is a less efficient use of server memory if reading the whole stream into memory. Use StreamReader.Read()
to be conservative with memory particularly if working with large files on a server.
using (System.Net.WebClient wc = new System.Net.WebClient())
{
try
{
using (System.IO.Stream stream = wc.OpenRead("http://www.prowaretech.com/"))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
string str = reader.ReadToEnd(); // could read one character at a time with reader.Read() which is more efficient with regard to memory usage
// do something with str
}
}
}
catch (System.Exception ex)
{
// check exception object for the error
}
}