AboutSQL Server, Analytics, .Net, Machine Learning, R, Python Archives
About Me
Mitch Wheat has been working as a professional programmer since 1984, graduating with a honours degree in Mathematics from Warwick University, UK in 1986. He moved to Perth in 1995, having worked in software houses in London and Rotterdam. He has worked in the areas of mining, electronics, research, defence, financial, GIS, telecommunications, engineering, and information management. Mitch has worked mainly with Microsoft technologies (since Windows version 3.0) but has also used UNIX. He holds the following Microsoft certifications: MCPD (Web and Windows) using C# and SQL Server MCITP (Admin and Developer). His preferred development environment is C#, .Net Framework and SQL Server. Mitch has worked as an independent consultant for the last 10 years, and is currently involved with helping teams improve their Software Development Life Cycle. His areas of special interest lie in performance tuning |
Thursday, January 31, 2008C# Code Snippet: Download a File Over HTTP
This code snippet was adapted from one of Jim Wilson's excellent "How Do I?" tutorials. It works with .NET Framework 2.0 (including the .NET Compact Framework CF 2.0 SP2), and I've successfully tested it on a Windows CE 4.2 device. You will probably want to add a bit more error handling:
/// <summary> /// Download a file from a URL to a local folder on a windows mobile device /// Note: Don't forget that mobile folders do not start with a drive letter. /// </summary> /// <param name="uri">e.g. http://www.someaddress/downloads/</param> /// <param name="filename">e.g. filetodownload.exe</param> /// <param name="localFolder">e.g. \temp\</param> /// <returns></returns> public static long FromHttp(string uri, string filename, string localFolder) { long totalBytesRead = 0; const int blockSize = 4096; Byte[] buffer = new Byte[blockSize]; if (!Directory.Exists(localFolder)) { Directory.CreateDirectory(localFolder); } try { HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename)); httpRequest.Method = "GET"; // if the URI doesn't exist, an exception will be thrown here... using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) { using (Stream responseStream = httpResponse.GetResponseStream()) { using (FileStream localFileStream = new FileStream(Path.Combine(localFolder, filename), FileMode.Create)) { int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead += bytesRead; localFileStream.Write(buffer, 0, bytesRead); } } } } } catch (Exception ex) { // You might want to handle some specific errors : Just pass on up for now... throw; } return totalBytesRead; } Comments welcome. |
ContactMSN, Email: mitch døt wheat at gmail.com LinksFavorites
Blogs |