簡體   English   中英

如何使用StreamReader在特定行之后讀取文本文件行

[英]How to read text file lines after Specific lines using StreamReader

我有一個文本文件,我正在使用StreamReader讀取。現在根據我的要求,無論我先讀了哪幾行,我都不想再次讀意味着我不想再次獲取該數據。所以我添加了File.ReadLines(FileToCopy).Count(); 代碼以首先獲取要讀取的行數。現在無論上面的代碼行返回什么行,我都想在那之后讀取。 這是我的代碼。

        string FileToCopy = "E:\\vikas\\call.txt";

        if (System.IO.File.Exists(FileToCopy) == true)
        {

            lineCount = File.ReadLines(FileToCopy).Count();

            using (StreamReader reader = new StreamReader(FileToCopy))
            {

            }
         }

我需要在這里指定什么條件。請幫助我。

       while ((line = reader.ReadLine()) != null)
        {

            var nextLines = File.ReadLines(FileToCopy).Skip(lineCount);

        if (line != "")
        {
        }

有一種更快的方法可以執行此操作,該方法不需要您讀取整個文件即可到達停止位置。 關鍵是要跟蹤文件的長度。 然后,您以FileStream打開文件,將其定位到先前的長度(即之前閱讀的末尾),然后創建一個StreamReader 所以看起來像這樣:

long previousLength = 0;

然后,當您要復制新內容時:

using (var fs = File.OpenRead(FileToCopy))
{
    // position to just beyond where you read before
    fs.Position = previousLength;

    // and update the length for next time
    previousLength = fs.Length;

    // now open a StreamReader and read
    using (var sr = new StreamReader(fs))
    {
        while (!sr.EndOfStream)
        {
            var line = sr.ReadLine();
            // do something with the line
        }
    }
}

如果文件變大這將節省您的大量時間。 例如,如果文件上次閱讀時大小為千兆字節,則File.ReadLines(filename).Skip(count)將花費20秒到達結尾,因此您可以閱讀下一行。 我上面描述的方法將花費更少的時間-可能不到一秒鍾。

這個:

lineCount = File.ReadLines(FileToCopy).Count();

將返回文件中的總行數,這對您沒有用,您需要存儲從文件中讀取的行數,然后每次再次讀取時,請使用Skip方法:

var nextLines = File.ReadLines("filaPath").Skip(lineCount);

您在這里不需要StreamReader 。例如,如果您是第一次讀取文件,請假設10行:

var lines = File.ReadLines(filePath).Take(10);
lineCount += 10;

第二次Skip10行,閱讀更多內容並更新lineCount

var nextLines = File.ReadLines(filePath).Skip(lineCount).Take(20);

lineCount += 20;

更籠統地說,您可以為此編寫一個方法,並在需要閱讀下幾行時調用它:

public  static string[] ReadFromFile(string filePath, int count, ref int lineCount)
{
    lineCount += count;
    return File.ReadLines(filePath).Skip(lineCount).Take(count).ToArray();
}

private static int lineCount = 0;
private static void Main(string[] args)
{
   // read first ten line
   string[] lines = ReadFromFile("sample.txt", 10, ref lineCount);

   // read next 30 lines
   string[] otherLines = ReadFromFile("sample.txt", 30, ref lineCount)
}

希望您能明白。

只需從您的新流中讀取lineCount行:

for(int n=0; n<lineCount; n++) 
{
    reader.ReadLine();
}

當您必須實際跳過N行(而不是N個字節)時,這是最簡單的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM