我收到此錯誤:進程無法訪問文件(...),因爲它正在被另一個進程使用。我試圖用 File.WriteAllText
;寫入文件ASP.NET C#並且之後不鎖定它
StreamWriter sw = new StreamWriter(myfilepath);
sw.Write(mystring);
sw.Close();
sw.Dispose();
;
using (FileStream fstr = File.Create(myfilepath))
{
StreamWriter sw = new StreamWriter(myfilepath);
sw.Write(mystring);
sw.Close();
sw.Dispose();
fstr.Close();
}
我所要做的就是訪問一個文件,然後關閉它。我可能犯了一個愚蠢的錯誤,但我想明白我做錯了什麼,爲什麼。如何確保文件已關閉並且不會再次導致此錯誤。
通過答案的幫助下,到目前爲止我這樣做:
using (FileStream fstr = File.Open(myfilepath,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fstr);
sw.Write(mystring);
sw.Close();
}
這似乎是更好,因爲它似乎關閉/停止我的文件的過程中,如果我嘗試訪問在第二時間的另一個文件I訪問該頁面。但是如果我第二次嘗試訪問同一個文件,它會再次出現錯誤。
以及第一個或第二個代碼段發生了什麼?如果您在StreamWriter上使用帶有使用的第一個片段,它應該可以工作,並且不需要您調用close或dispose。看到這裏:http://stackoverflow.com/questions/7710661/do-you-need-to-call-flush-on-a-stream-if-you-are-using-using-statement/7710686#7710686 – 2012-07-27 11:41:14
你的第二種方法有點奇怪。你正在創建一個FileStream,但你永遠不會使用它('StreamWriter sw = new StreamWriter(fstr);')。無論如何,你也不需要處理它,因爲你正在使用'using-statement'。 – 2012-07-27 11:44:29