簡體   English   中英

如何刪除文本文件中的最后一行?

[英]How to delete last line in a text file?

每次從 3rd 方程序生成日志文件時,我都有一個簡單的日志文本文件,擴展名為 .txt,在該文本文件的末尾有一個空白行。

因此,是否有任何方法或代碼可以用來刪除文本文件的最后一行?

日志文本文件的示例:

Sun Jul 22 2001 02:37:46,73882,...b,r/rrwxrwxrwx,0,0,516-128-3,C:/WINDOWS/Help/digiras.chm
Sun Jul 22 2001 02:44:18,10483,...b,r/rrwxrwxrwx,0,0,480-128-3,C:/WINDOWS/Help/cyycoins.chm
Sun Jul 22 2001 02:45:32,10743,...b,r/rrwxrwxrwx,0,0,482-128-3,C:/WINDOWS/Help/cyzcoins.chm
Sun Jul 22 2001 04:26:14,174020,...b,r/rrwxrwxrwx,0,0,798-128-3,C:/WINDOWS/system32/spool/drivers/color/kodak_dc.icm

怎么樣:

var lines = System.IO.File.ReadAllLines("...");
System.IO.File.WriteAllLines("...", lines.Take(lines.Length - 1).ToArray());

解釋:

從技術上講,您不會從文件中刪除一行。 您讀取文件的內容並將它們寫回,但不包括要刪除的內容。

這段代碼的作用是將所有行讀入一個數組,然后將這些行寫回到文件中,只排除最后一行。 (Take() 方法(LINQ 的一部分)采用指定的行數,在我們的例子中是長度 - 1)。 在這里, var lines可以讀作String[] lines

使用此方法刪除文件的最后一行:

public static void DeleteLastLine(string filepath)
{
    List<string> lines = File.ReadAllLines(filepath).ToList();

    File.WriteAllLines(filepath, lines.GetRange(0, lines.Count - 1).ToArray());

}

編輯:意識到 lines 變量以前不存在,所以我更新了代碼。

如果要從文件中刪除最后 N 行而不將所有加載到內存中

int numLastLinesToIgnore = 10;
string line = null;
Queue<string> deferredLines = new Queue<string>();
using (TextReader inputReader = new StreamReader(inputStream))
using (TextWriter outputReader = new StreamWriter(outputStream))
{
    while ((line = inputReader.ReadLine()) != null)
    {
        if (deferredLines.Count() == numLastLinesToIgnore)
        {
            outputReader.WriteLine(deferredLines.Dequeue());
        }

        deferredLines.Enqueue(line);
    }
    // At this point, lines still in Queue get lost and won't be written
}

發生的情況是您緩沖隊列中每個新行的維度為numLastLinesToIgnore並從中彈出一行僅在隊列已滿時寫入。 您實際上預讀了文件,並且可以在到達文件末尾之前停止numLastLinesToIgnore行,而無需提前知道總行數

請注意,如果文本小於numLastLinesToIgnore ,則結果為空。

我想出了一個鏡像解決方案: 從文本文件中刪除特定行?

您不能刪除行尾,因為 File.WriteAllLines 會自動添加它,但是,您可以使用此方法:

public static void WriteAllLinesBetter(string path, params string[] lines)
{
    if (path == null)
        throw new ArgumentNullException("path");
    if (lines == null)
        throw new ArgumentNullException("lines");

    using (var stream = File.OpenWrite(path))
    using (StreamWriter writer = new StreamWriter(stream))
    {
        if (lines.Length > 0)
        {
            for (int i = 0; i < lines.Length - 1; i++)
            {
                writer.WriteLine(lines[i]);
            }
            writer.Write(lines[lines.Length - 1]);
        }
    }
}

這不是我的,我在.NET File.WriteAllLines找到它在文件末尾留下空行

我剛剛從其他網站上找到了解決方案,這是網址https://stackoverrun.com/cn/q/627722

用少量的行,你可以很容易地使用這樣的東西

string filename = @"C:\Temp\junk.txt";
string[] lines = File.ReadAllLines(filename);

但是,隨着文件變大,您可能希望使用這樣的方式將數據傳入和傳出

string filename = @"C:\Temp\junk.txt";
string tempfile = @"C:\Temp\junk_temp.txt";

using (StreamReader reader = new StreamReader(filename))
{                
       using (StreamWriter writer = new StreamWriter(tempfile))
       {
           string line = reader.ReadLine();

           while (!reader.EndOfStream)
           {
               writer.WriteLine(line);
               line = reader.ReadLine();
           } // by reading ahead, will not write last line to file
       }
}

File.Delete(filename);
File.Move(tempfile, filename);

這應該是使用大文件的最佳選擇。

using (StreamReader source = new StreamReader(sourceFileName))
        {
            using (StreamWriter sw = new StreamWriter(newFileName))
            {
                do
                {

                    line = source.ReadLine();

                    if (source.Peek() > -1)
                    {
                        sw.WriteLine(line);
                    }
                    else
                    {
                        File.AppendAllText("RemovedLastLine.txt", line);
                    }

                }
                while (line != null);
            }
        }

暫無
暫無

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

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