2012-07-27 63 views
4

我收到此錯誤:進程無法訪問文件(...),因爲它正在被另一個進程使用。我試圖用 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訪問該頁面。但是如果我第二次嘗試訪問同一個文件,它會再次出現錯誤。

+0

以及第一個或第二個代碼段發生了什麼?如果您在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

+1

你的第二種方法有點奇怪。你正在創建一個FileStream,但你永遠不會使用它('StreamWriter sw = new StreamWriter(fstr);')。無論如何,你也不需要處理它,因爲你正在使用'using-statement'。 – 2012-07-27 11:44:29

回答

1

我想感謝大家的幫助。 事實上,除了這段代碼之外,我發現在上面的代碼之後,我還有一個stremReader在其他地方打開。最後我改變了代碼,我以前還爲此:

using (FileStream fstr = File.Open(myfile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) 

        { 
         StreamWriter sw = new StreamWriter(fstr); 
         sw.Write(mystring); 
         sw.Flush(); 
         sw.Dispose(); 
        } 

和我的StreamReader我這樣做:

StreamReader sr = new StreamReader(myfile); 
string sometext = sr.ReadToEnd(); 
sr.Dispose(); 

我也用這個:

File.ReadAllText(myfile); 

如果有是我可以以更好的方式完成的事情,請告訴我。 非常感謝。

2

「因爲它正在使用另一個進程」這是線索。你有機會在記事本中打開文件嗎?

當您打開允許讀者閱讀的文件時,您可能需要設置共享模式,並只詢問您需要的權限(寫入權限)。

0

試試這個

FileStream fs = new FileStream(myfilepath, FileMode.Create, FileAccess.Write);    
byte[] bt = System.Text.Encoding.ASCII.GetBytes(mystring); 
fs.Write(bt, 0, bt.Length); 
fs.Close(); 
3

爲什麼不直接使用:

System.IO.File.WriteAllText(myfilepath, mystring"); 

這不應該鎖定您的文件。

內部WriteAllText使用FileShare.Read並在完成寫入後立即釋放該鎖。

相關問題