C. net implements the method of downloading files from internet in Winform
- 2021-07-22 11:04:27
- OfStack
This article illustrates the C #. net implementation of downloading files from internet in Winform. Share it for your reference. The details are as follows:
I made a general software automatic upgrade program, which needs to download files from the given url to the local, share 1.
/// <summary>
/// Download a file
/// </summary>
/// <param name="URL"> Download file address </param>
/// <param name="Filename"> Download and Save As (Full Path) </param>
private bool DownloadFile(string URL, string filename)
{
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
myrp.Close();
Myrq.Abort();
return true;
}
catch (System.Exception e)
{
writeLogFile(e.Message, true);
return false;
}
}
I hope this article is helpful to everyone's C # programming.