【问题标题】:Read last line from website without saving file on disk从网站读取最后一行而不将文件保存在磁盘上
【发布时间】:2017-12-12 03:43:29
【问题描述】:

我的网站包含许多大型 CSV 文件(每个文件最多 100,000 行)。从每个 CSV 文件中,我需要读取文件中的最后一行。当我在读取文件内容之前将文件保存在磁盘上时,我知道如何解决该问题:

                var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
            var client = new System.Net.WebClient();
            var tempFile = System.IO.Path.GetTempFileName();
            client.DownloadFile(url, tempFile);
            var lastLine = System.IO.File.ReadLines(tempFile).Last();

有什么方法可以在不将临时文件保存在磁盘上的情况下获取最后一行? 我试过了:

using (var stream = client.OpenRead(seriesUrl))
{
    using (var reader = new StreamReader(stream))
    {
        var lastLine = reader.ReadLines("file.txt").Last();
    }
}

但 StreamReader 类没有 ReadLines 方法...

【问题讨论】:

标签: c# csv io webclient streamreader


【解决方案1】:

这对我有用,虽然服务没有返回数据(仅限 CSV 的标题):

public void TestMethod1()
{
    var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24";
    var client = new System.Net.WebClient();

    using (var stream = client.OpenRead(url))
    {
        using (var reader = new StreamReader(stream))
        {
            var str = reader.ReadToEnd().Split('\n').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault();

            Debug.WriteLine(str);
            Assert.IsNotEmpty(str);
        }
    }

}

【讨论】:

    【解决方案2】:

    StreamReader 没有ReadLines 方法,但它确实有一个ReadLine method 来从流中读取下一行。您可以使用它从远程资源中读取最后一行,如下所示:

    using (var stream = client.OpenRead(seriesUrl))
    {
        using (var reader = new StreamReader(stream))
        {
            string lastLine;
    
            while ((lastLine = reader.ReadLine()) != null)
            {
                // Do nothing...
            }
    
            // lastLine now contains the very last line from reader
        }
    }
    

    使用ReadLine 一次读取一行将比StreamReader.ReadToEnd 使用更少的内存,StreamReader.ReadToEnd 会将整个流作为string 读入内存。对于 100,000 行的 CSV 文件,这可能会占用大量内存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 2010-10-26
      • 1970-01-01
      相关资源
      最近更新 更多