user5404910
user5404910

Reputation:

How to read StreamReader text line by line

I have a text file hosted and this file have a organized string like this:

I'm getting all content from this file with following function:

        private static List<string> lines;

        private static string DownloadLines(string hostUrl)
        {
            var strContent = "";

            var webRequest = WebRequest.Create(hostUrl);

            using (var response = webRequest.GetResponse())
            using (var content = response.GetResponseStream())
            using (var reader = new StreamReader(content))
            {
                strContent = reader.ReadToEnd();
            }

             lines = new List<string>();

             lines.Add(strContent);

            return strContent;

        }


// Button_click

        DownloadLines("http://address.com/folder/file.txt");

            for (int i = 0; i < lines.Count; i++)
            {

                lineAux = lines[0].ToString();

                break;

            }

            Console.WriteLine(lineAux);

Then, how I can access for example the first index like text inside this large organized string that is returned by this method?

Upvotes: 7

Views: 33255

Answers (1)

Mostafiz
Mostafiz

Reputation: 7352

You can read text file line by line this way

private static List<string> DownloadLines(string hostUrl)
    {

    List<string> strContent = new List<string>();

    var webRequest = WebRequest.Create(hostUrl);

    using (var response = webRequest.GetResponse())
    using (var content = response.GetResponseStream())
    using (var reader = new StreamReader(content))
        {
            while (!reader.EndOfStream)
            {
                strContent.Add(reader.ReadLine());
            }
        }

    return strContent;

}

after returning this list from the method you can access the text line using list index

Upvotes: 23

Related Questions