473,585 Members | 2,657 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

1 New Member
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 5317
vishal1082
92 New Member
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...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.
Jan 4 '10 #2
piyusht
8 New Member
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
6001
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 error. If is possibile to mke save in JAVA then is posible tha make save in any
2
16401
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 object, with g = pictureBox.CreateGraphic, and draw lines g.drawLines(....) But when saving the picture, the new picture have no lines, it is only...
2
5448
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 very hard time in finding some out-of-the box software to do what I consider to be something relatively simple. I have about 50 Windows NT 4.0...
7
4134
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. Also trying to avoid setting it to a bigint in the server. Casting an int to an uint use to work in C++. System.Data.SqlClient.SqlConnection...
4
6222
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
4095
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" My machine is running Windows 2003. My colleagues are using the same hardware and software as I do, but I am the only one running into this...
4
10992
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 greatly appreciated. I have an .ASPX.CS in which I am trying to open an XML file (which already contains content), making some alterations to the...
3
9955
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 must to do to save stream object s to file ?
0
7908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7836
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8199
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8336
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7950
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6606
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2343
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.