vincentchang Posted March 13, 2006 Posted March 13, 2006 (edited) Dear All, I am using WebClient in my Visual Studio .Net 2003 project to download an image from the Internet. The following is my function: public static bool downloadFile(string URL, ref string fileName) { bool result = true; System.Net.WebClient webClient = new System.Net.WebClient(); try { string[] temp; temp = URL.Split('/'); fileName = Application.StartupPath + "\\tempimage\\" + temp[temp.Length-1]; webClient.Credentials = System.Net.CredentialCache.DefaultCredentials; webClient.DownloadFile(URL, fileName); } catch (System.Exception ex) { result = false; } finally { webClient.Dispose(); } return result; } The above function works most of t he time but sometimes I got the following exception: System.Net.WebException: The underlying connection was closed: The server committed an HTTP protocol violation. at System.Net.HttpWebRequest.CheckFinalStatus() at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.HttpWebRequest.GetResponse() at System.Net.WebClient.DownloadFile(String address, String fileName) at WindowsApplication4.Form11.downloadFile(String URL, String fileName) in g:\project\visual studio projects\windowsapplication4\windowsapplication4\form11.cs:line 392 Do anyone know what wrong is the function? Thanks very much for your help. Regards, Vincent Edited March 13, 2006 by PlausiblyDamp Quote
Gill Bates Posted July 4, 2006 Posted July 4, 2006 You seem to be passing an absolute local path as the file name. I don't see how the remote server is going to be able to use this. Since you say you are downloading the file from the Internet why not just use the URL for the image? string url = "http://localhost/images/test.jpg" // Download the file // (using System.Net) WebClient client = new WebClient(); client.Credentials = System.Net.CredentialCache.DefaultCredentials; byte[] data = client.DownloadData(url); // write the file to the temp directory // (using System.IO) string path = Path.GetTempPath() + @"\image.jpg"; FileStream fileStream = new FileStream(path, FileMode.Create); fileStream.Write(data, 0, data.Length); fileStream.Close(); // open the file // (using System.Diagnostics) Process process = new Process(); process.StartInfo.FileName = path; process.Start(); Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.