簡體   English   中英

通過FileShare鎖定時讀取,刪除和寫入文件FileShare.None?

[英]Read, delete, and write to file while locking via FileShare FileShare.None?

這可能是以前問過的,所以我先向您道歉。 但是,我覺得這里有很多問題的獨特之處,因此我認為沒有必要解決這個問題。

我正在嘗試使用FileStream方法打開文件。 我需要從外部讀寫操作中以鎖定狀態打開此文件,這就是為什么在打開文件時使用FileShare.None屬性的原因。 打開並鎖定文件后,我將文件的內容逐行讀取到字符串數組中。 我根據需要更新的信息來更改其中一行,然后將這些行寫回到文件中。

我遇到的問題是,在讀取的原始行之后追加了編寫的行。 讀完文件后,我需要擦除文件,以便回寫的內容是文件中唯一的內容。

我很困惑,因為我不想關閉FileStream並重新打開它以只寫(應該清除文件),因為那會釋放我對文件的鎖定。

FileStream fs = new FileStream("trains.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

string[] lines = new string[trains.Length];

//Loop through all lines in the file
for (int i = 0; i < lines.Length; i++)
{
    lines[i] = sr.ReadLine();

    /*If the ID of the train in the file matches the parameter, then
        set the line to the InfoLine of the train.*/
    if (lines[i][0].ToString() == train.ID().ToString())
    {
        lines[i] = train.GetInfoLine();
    }
}

//Write back the lines to the file
for (int i = 0; i < lines.Length; i++)
{
    sw.WriteLine(lines[i]);
}

sw.Close();
sr.Close();
fs.Close();

在上面的代碼中,trains.Length只是類對象數組的長度。 我有GetInfoLine()方法,該方法返回要寫入文件的信息字符串。

我會這樣做:

string line = "";
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

List<string> lines = new List<string>();

while ((line = sr.ReadLine()) != null)
{
    line = "*" + line; //Do your processing
    lines.Add(line);
}

fs.SetLength(0);

foreach (var newline in lines)
{
    sw.WriteLine(newline);
}
sw.Flush();
fs.Close();

參見fs.SetLength(0);

暫無
暫無

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

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