【问题标题】:How to read StreamReader text line by line如何逐行读取 StreamReader 文本
【发布时间】:2016-09-03 09:13:07
【问题描述】:

我托管了一个文本文件,这个文件有一个有组织的字符串,如下所示:

  • 第一行
  • 第二行
  • 第三行
  • 第四行
  • 第六行
  • 第七行
  • ........

我正在使用以下功能从该文件中获取所有内容:

        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);

那么,我如何访问这个方法返回的这个有组织的大字符串中的第一个索引,例如文本?

【问题讨论】:

    标签: c# .net text streamreader


    【解决方案1】:

    这样可以逐行读取文本文件

    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;
    
    }
    

    从方法返回此列表后,您可以使用列表索引访问文本行

    【讨论】:

      猜你喜欢
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 2014-06-13
      • 2011-11-02
      • 2015-05-21
      • 2022-11-05
      相关资源
      最近更新 更多