473,386 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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.
Jan 3 '10 #1
2 5305
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:
Expand|Select|Wrap|Line Numbers
  1.  
  2.        private void Download(string URL, string SaveTo)
  3.         {
  4.             //URL = URL of the file to download, dont forget to add http://www. before it...
  5.             //SaveTo = Address of the location to save the downloaded file...
  6.             System.Net.WebClient w = new System.Net.WebClient();
  7.             w.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(w_DownloadProgressChanged);
  8.             w.DownloadFileCompleted += new AsyncCompletedEventHandler(w_DownloadFileCompleted);
  9.             w.DownloadFileAsync(new Uri(URL), SaveTo);
  10.         }
  11.  
  12.         void w_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  13.         {
  14.             //...do anything here when the download starts...
  15.         }
  16.  
  17.         void w_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
  18.         {
  19.             //...do anything here when progress changes of the download, you can use the e.ProgressPercentage to get the percentage of progress done
  20.         }
You can remove the line
Expand|Select|Wrap|Line Numbers
  1. 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
Expand|Select|Wrap|Line Numbers
  1. w.DownloadFileCompleted += new AsyncCompletedEventHandler(w_DownloadFileCompleted);
if you dont want to do anything when the download is completed...also 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.
Jan 4 '10 #2
If HTTPS is used then WebClient will fail. In that case use the following code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. public static bool DownloadFile(string url, string path)
  3.         {
  4.  
  5.             try
  6.             {
  7.                 if (ServicePointManager.ServerCertificateValidationCallback == null)
  8.                 {
  9.                     ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CustomXertificateValidation);
  10.                 }
  11.  
  12.                 // Create a request for the URL. 
  13.                 WebRequest request = WebRequest.Create(url);
  14.                 // If required by the server, set the credentials.
  15.                 request.Credentials = CredentialCache.DefaultCredentials;
  16.  
  17.                 // Get the response.
  18.                 byte[] buffer = new byte[4096];
  19.                 WebResponse response = request.GetResponse();
  20.                 // Display the status.
  21.                 if (((HttpWebResponse)response).StatusDescription.ToUpper() == "OK")
  22.                 {
  23.                     Logger.WriteToLog("Response receieved from server.", true, LogSeverityLevel.Verbose);
  24.                     //Check content length otherwise 0 KB file will be created which will cause problems later on.
  25.                     if (response.ContentLength == 0)
  26.                     {
  27.                         response.Close();
  28.                         Logger.WriteToLog("No content found in response.", true, LogSeverityLevel.Error);
  29.                         return false;
  30.                     }                    
  31.                     // Get the stream containing content returned by the server.
  32.                     using (Stream dataStream = response.GetResponseStream())
  33.                     {
  34.  
  35.                         string shortPath = UtilityFunctions.GetShortPath(path);
  36.                         FileInfo info = new FileInfo(shortPath);
  37.                         if (!info.Directory.Exists)
  38.                             info.Directory.Create();
  39.  
  40.                         using (FileStream fs = File.Create(path))
  41.                         {
  42.                             int count = 0;
  43.                             do
  44.                             {
  45.                                 count = dataStream.Read(buffer, 0, buffer.Length);
  46.                                 fs.Write(buffer, 0, count);
  47.  
  48.                             } while (count != 0);
  49.  
  50.                             fs.Close();
  51.                         }
  52.                     }
  53.                 }
  54.                 response.Close();               
  55.                 return true;
  56.             }
  57.             catch (Exception ex)
  58.             {                
  59.                 return false;
  60.             }
  61.         }
  62.  
  63. private static bool CustomXertificateValidation(object sender, X509Certificate cert, X509Chain chain, System.Net.Security.SslPolicyErrors error)
  64.         {
  65.                 return true;
  66.         }
  67.  
Jan 5 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Robert Bralic | last post by:
Hello, I writed small graphical editor for probabilystic networks in JAVA, but there was problem with making save file inJAVA. I thinked about it and I concluded that Save in JAVA is great...
2
by: Michael Lehar | last post by:
Hallo I have a pictureBox with a picture loaded from file, then I draw some lines on the picture, and then I want to save the new picture. Befor I can draw lines I have to create a Graphics...
2
by: Joey Powell | last post by:
I would like to know if anyone has any information on how to write C# code to "intercept" http traffic to and from websites. Not that I'm trying to re-invent the wheel here, but I am having a...
7
by: John J. Hughes II | last post by:
I need to save a DWORD to the sql server, the below posts an error, any suggestions on what I am doing wrong. I have the column in the sql server defined as an int since unsigned int is not valid....
4
by: Jaime | last post by:
I have to save a dataset to xml and for efficiency I like to get rid of the namespace prefix d2p1: can any one help thanks jaime
3
by: David N | last post by:
I got a solution that contains about 30 projects, three of which cannot be open. When I open the project, I always receive the error message "Unable to get the project file from the Web Server" ...
4
by: Carl Williams | last post by:
Hope someone can help with this... I have looked at all the newsgroup articles and put into practice all the suggestions but to no good. I am pretty new to CSharp and .Net so any help would be...
3
by: terrorix | last post by:
Hi, I have function which return instance of object Stream and i want that stream object to save to file. How can i do that? my code is: Stream s = MyGetStream(); my question is what i...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.