儘管有其他文章,但從一個文件中讀取並「同時」寫入文件沒有任何問題。理解問題的關鍵是打開文件時使用的模式。
看看你的代碼更明確的變體:
using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
using (StreamReader rd = new StreamReader(fileStream))
{
using (StreamWriter wr = new StreamWriter(fileStream))
{
string line = null;
while ((line = rd.ReadLine()) != null)
{
if (String.Compare(line, active_user) == 0)
{
//do nothing
}
else
{
wr.WriteLine(active_user);
//If you flush what you write then you will see it via the reader.
//Comment out for better performance. Keep in mind, that writing
//into a file will lead to occasional flush which affects the
//reader. Implicit Flush happens once you write more than the
//buffer of the writer suggests.
wr.Flush();
}
}
}
}
}
正如你所看到的,它是從文件被打開的方式你的代碼不同。我只是希望明確指定我打開文件的模式。 似乎StreamReader在沒有「共享」的情況下隱式打開文件,即不允許其他人打開它,這是可以的,因爲它希望保護您免受意外結果的侵害。因此,這種隱式方法不適合你稍微「複雜」的場景。明確打開文件的竅門。 請注意,File.Open允許您打開文件並仍允許其他線程(其他應用程序)打開文件。全取決於你。
現在到你的代碼的邏輯。 StreamReader從頭開始讀取流。 StreamWriters會顯示流內容的結尾。都保持和維護自己的流位置。因此,代碼將爲文件的每行不包含「active_user」的行添加一行包含「active_user」的行。我無法想象這是一個實際的原因。
我正在檢查一切,但沒有找到任何使用該文件的應用程序。有沒有辦法強制所有進程以編程方式釋放文件? – DoIt
您正在同時閱讀和寫入文件。 – tnw
這是錯誤的方法。寫入一個新的臨時文件,然後刪除舊的並將新名稱重命名爲舊名稱。 –