簡體   English   中英

刪除 StreamWriter 的最后一行?

[英]Delete the last line of a StreamWriter?

我知道當我們使用 StreamWriter 時,根據定義,這是在其中寫入,但事實是,在某些時候我有義務刪除我的流寫入器的最后一行......

我發現以下代碼(在 SO 上)運行良好:

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

但問題是我不能在我的:

using (StreamWriter sw = new StreamWriter(pluginQmlFileName, true))
{
    [...]
}

部分。

有沒有辦法刪除using {}部分的最后一行,還是必須保留我的實際代碼?

我不認為 StreamWriter 允許您這樣做,但也許您可以制作自己的流包裝器來實現此行為? 也就是說,它會將最后一行保留在內存中,並且僅在另一行進入時才將其寫出。

您可以在閱讀完所有內容后刪除最后一行:

var lines = System.IO.File.ReadLines(pluginQmlFileName);

// will need changing to remove from the array if using ReadAllLines instead of ReadLines
lines = lines.RemoveAt(lines.Count - 1);

這似乎也適用於我:

//您必須嘗試關閉該文件的所有打開流(如果有) //如果您在內部using (StreamWriter sw = .... ) {....}using (StreamWriter sw = .... ) {....} //attempt => sw.close(); //然后

FileStream fs = new FileStream(filePath , FileMode.Open, FileAccess.ReadWrite);
fs.SetLength(fs.Length - 1);
fs.Close();

不,您不能從 StreamWriter 打開的流中刪除任何數據。 StreamWriter 旨在寫入文件,因此您無法明確刪除任何內容。

因此必須使用其他類來讀取文件內容,然后由於StreamWriter 類繼承自TextWriter 類,您應該能夠使用WriteLine(string)方法,但這沒有意義,因為您已經有一個非常好的工作代碼。

// read all lines
// ...
var allExceptLast = lines.Take(lines.Length - 1);
foreach(var line in allExceptLast)
{
   writer.WriteLine(line);
}

這就是我解決問題的方式:

StreamWriter myFile = new StreamWriter(fileName, false);
int countLines = 0;
foreach (var line in lines)
{
    countLines++;
    if (countLines == lines.Count)
    {
        //Write doesn't insert "/r/n" on the end of line
        myFile.Write(line.ToString());
    }
    else
    {
        //WriteLine insert "/r/n" on the end of a line
        myFile.WriteLine(line.ToString());
    }
}

好吧,在上面的代碼中, lines實際上是一個字符串數組,因為ReadAllLines返回一個字符串數組。

與其考慮“刪除最后一行”,我寧願考慮“不寫最后一行”,那么您可以做什么:

string[] lines = ...; // Note that I'm using an array here!

using (...)
{
    for (int i = 0; i < lines.Length; i++)
    {
        if (i < lines.Length-1 || !condition)
            sw.WriteLine(lines[i]);
    }
}

這會將所有行寫入倒數第二行。 最后一行僅在條件為假時寫入。

暫無
暫無

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

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