Click here to Skip to main content
15,915,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
try
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpRequest.Credentials = CredentialCache.DefaultCredentials;
                
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

                System.IO.Stream dataStream = httpResponse.GetResponseStream();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(dataStream);

                String data = streamReader.ReadToEnd();
                
                byte[] buffer = new byte[data.Length];

                for (int i = 0; i < data.Length; i++)
                    buffer[i] = (byte)data[i];
                
                dataStream.Close();
                streamReader.Close();
                
                FileStream fs = new FileStream("filename.txt", FileMode.CreateNew);
                BinaryWriter bw = new BinaryWriter(fs);

                for (int i = 0; i < buffer.Length; i++)
                    bw.Write(buffer[i]);

                streamReader.Close();
                httpResponse.Close();
            }
            catch (Exception pe)
            {
                System.Windows.Forms.MessageBox.Show(pe.Message);
            }

This is code is working, when downloading a text,word and excel files, if i am Downloading a .cab or .exe files means it shows an exception "Value out of range" Actually i want to download the .cab files and .exe files, How to Download That???
Thanks
Posted
Updated 19-Sep-12 7:38am
v3

1 solution

you cannot convert binary files to string and then write it to file.

C#
using (FileStream destination = File.Open(@"some.exe",FileMode.CreateNew))
{
dataStream.CopyTo(destination);
}
 
Share this answer
 
v3
Comments
lachu88 20-Sep-12 11:30am    
Sir!!!!

Thanks

PLz Tell me clearly!!!!
Kuthuparakkal 20-Sep-12 11:33am    
try

{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(uri);
httpRequest.Credentials = CredentialCache.DefaultCredentials;

HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

System.IO.Stream dataStream = httpResponse.GetResponseStream();
using (FileStream destination = File.Open(@"some.exe",FileMode.CreateNew))

{
dataStream.CopyTo(destination);
}
httpResponse.Close();
}
catch (Exception pe)
{
System.Windows.Forms.MessageBox.Show(pe.Message);
}
lachu88 20-Sep-12 11:33am    
Thanks I will try it!!!!
lachu88 20-Sep-12 11:44am    
Thank You!!! Let me Try This Tomorrow !!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900