从网站读取最后一行而不将文件保存在磁盘上

Read last line from website without saving file on disk

我的网站有许多大型 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 class 没有 ReadLines 方法...

这对我有用,尽管该服务没有 return 数据(仅 Headers 的 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);
        }
    }

}

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

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