How can I save a file from the internet using csharp?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • yanksrock528
    New Member
    • Jan 2010
    • 1

    How can I save a file from the internet using csharp?

    I am writing a program, and i would like to save an xml file that is on the internet now, to my computer in this csharp program. Something else that might help is if i could get the csharp xml reader to work on files on the internet. I would like to read the attributes of xml files and for some reason that is only working when i read the files on my local drive. I am fairly new to csharp and all that i know i have tought myself through the internet. Any help with anyone of these problems would be greatly appreciated.
  • vishal1082
    New Member
    • Apr 2009
    • 92

    #2
    hey!, i guess you wanna download some file from internet to the computer.. you can use WebClient class which is System.Net namespace, heres the code:
    Code:
     
           private void Download(string URL, string SaveTo)
            {
                //URL = URL of the file to download, dont forget to add http://www. before it...
                //SaveTo = Address of the location to save the downloaded file...
                System.Net.WebClient w = new System.Net.WebClient();
                w.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(w_DownloadProgressChanged);
                w.DownloadFileCompleted += new AsyncCompletedEventHandler(w_DownloadFileCompleted);
                w.DownloadFileAsync(new Uri(URL), SaveTo);
            }
    
            void w_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
            {
                //...do anything here when the download starts...
            }
    
            void w_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
            {
                //...do anything here when progress changes of the download, you can use the e.ProgressPercentage to get the percentage of progress done
            }
    You can remove the line
    Code:
    w.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(w_DownloadProgressChanged);
    if you dont want to do anything on progress changed...also delete the event for it.

    You can also remove the line
    Code:
    w.DownloadFileCompleted += new AsyncCompletedEventHandler(w_DownloadFileCompleted);
    if you dont want to do anything when the download is completed...als o delete the event for it.

    Hope this helps :) I really dont know any way of directly reading XML from the InterWebz, but after downloading XML with this code you can read/write/edit the XML since it will be on your local hard disk.

    Comment

    • piyusht
      New Member
      • Jan 2010
      • 8

      #3
      If HTTPS is used then WebClient will fail. In that case use the following code:

      Code:
      public static bool DownloadFile(string url, string path)
              {
      
                  try
                  {
                      if (ServicePointManager.ServerCertificateValidationCallback == null)
                      {
                          ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CustomXertificateValidation);
                      }
      
                      // Create a request for the URL. 
                      WebRequest request = WebRequest.Create(url);
                     [B] // If required by the server, set the credentials.
                      request.Credentials = CredentialCache.DefaultCredentials;[/B]
                      
                      // Get the response.
                      byte[] buffer = new byte[4096];
                      WebResponse response = request.GetResponse();
                      // Display the status.
                      if (((HttpWebResponse)response).StatusDescription.ToUpper() == "OK")
                      {
                          Logger.WriteToLog("Response receieved from server.", true, LogSeverityLevel.Verbose);
                          //Check content length otherwise 0 KB file will be created which will cause problems later on.
                          if (response.ContentLength == 0)
                          {
                              response.Close();
                              Logger.WriteToLog("No content found in response.", true, LogSeverityLevel.Error);
                              return false;
                          }                    
                          // Get the stream containing content returned by the server.
                          using (Stream dataStream = response.GetResponseStream())
                          {
      
                              string shortPath = UtilityFunctions.GetShortPath(path);
                              FileInfo info = new FileInfo(shortPath);
                              if (!info.Directory.Exists)
                                  info.Directory.Create();
      
                              using (FileStream fs = File.Create(path))
                              {
                                  int count = 0;
                                  do
                                  {
                                      count = dataStream.Read(buffer, 0, buffer.Length);
                                      fs.Write(buffer, 0, count);
      
                                  } while (count != 0);
      
                                  fs.Close();
                              }
                          }
                      }
                      response.Close();               
                      return true;
                  }
                  catch (Exception ex)
                  {                
                      return false;
                  }
              }
      
      private static bool CustomXertificateValidation(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
              {
                      return true;
              }

      Comment

      Working...