Tuesday, February 14, 2012

Download remote file using asp.net and C#.net

 

 

Download remote file using C#.net in windows application.

 

Following code will help for downloading remote file.

private static int DownloadFile(String remoteFilename, String localFilename)

{

int bytesProcessed = 0;

Stream remoteStream = null;

Stream localStream = null;

WebResponse response = null;

try

{

WebRequest request = WebRequest.Create(remoteFilename);

if (request != null)

{

response = request.GetResponse();

if (response != null)

{

remoteStream = response.GetResponseStream();

localStream = File.Create(localFilename);

 

byte[] buffer = new byte[1024];

int bytesRead;

do

{

bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

localStream.Write(buffer, 0, bytesRead);

bytesProcessed += bytesRead;

} while (bytesRead > 0);

}

}

}

catch (Exception ex)

{

string strMsg = ex.Message;

}

finally

{

if (response != null) response.Close();

if (remoteStream != null) remoteStream.Close();

if (localStream != null) localStream.Close();

}

return bytesProcessed;

}

}

 

For web application following method code will help

 

private Void DownloadFile()

{

string remoteImageUrl = "http://www.toptechreviews.net/wp-content/uploads/2011/06/Microsoft.png";

string strRealname = Path.GetFileName(remoteImageUrl);

string exts = Path.GetExtension(remoteImageUrl);

WebClient webClient = new WebClient();

webClient.DownloadFile(remoteImageUrl,

Server.MapPath("~/im/") + strRealname + exts);

}

in web.config we need set following configuration

  <system.net>

    <defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>

  </system.net>

 

 

 

No comments: