Tuesday, January 11, 2011

Asp.Net Reading File From Url

In this article is about Reading file from URL specially Text of CSV files, which we can directly read for the source and convert them into table. By doing this we generally avoid file handling, saving the file and then reading it again. WebRequest class of System.Net library is used to read remotely hosted text file or csv file.

We simply need to use following function which will read remote file and put it in a string format. String is named as output string.

WebRequest req = WebRequest.Create(YOURURL);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        string output = string.Empty;
        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);
        }

We are following simple steps in Asp.net for Reading file from URL.
  1. Identify the URL and create WebRequest Object
  2. Get the Response Stream 
  3. Encoding it in Appropriate Unicode format
  4. Reading the Data Stream.
  5. Finally getting the whole text string in one string variable i.e. "output" in this case.
It is very easy to in Asp.net to Read file from Url, as we have seen in above code. We can write our logic to manipulate the string.
Submit this story to DotNetKicks

1 comments:

joseph September 7, 2011 at 4:09 PM  

Thanks for sharing such useful information. The information provided is very very niche and this information is not available so easily. Therefore I thank the writer for the useful input.


php development