5

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

  • First line
  • Second line
  • Third line
  • Fourth line
  • Sixth line
  • Seventh line
  • ....................

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?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42

1 Answers1

20

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

Mostafiz
  • 7,243
  • 3
  • 28
  • 42