Home » General

Reading a file from external url – ASP .NET

14 February 2010 1,803 views No Comment

Often times you might need to read a file from another website server. For example reading a inventory data file from a vendor website. Here is a sample code to achieve that.

WebResponse result = null;
string output = “”;

try
{
WebRequest req = WebRequest.Create(“http://www.website.com/filename.txt”);
result = req.GetResponse();
Stream ReceiveStream = result.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding(“utf-8″);
StreamReader sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, read.Length);
while (count > 0)
{
String str = new String(read, 0, count);
output += str;
count = sr.Read(read, 0, read.Length);
}
}
catch (Exception)
{
Response.Write(“get failed”);
}
if (result != null)
{
result.Close();
}

Response.Write(output);

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.