2014-10-04 15 views
2

我試圖創建和使用下面的代碼如何建立txt文件,並把它寫C#asp.net

System.IO.Directory.CreateDirectory(Server.MapPath("~\\count")); 

using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create)) 
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt")) 
{ 
    sw.Write("101"); 
} 

string _count = System.IO.File.ReadAllText("~/count/count.txt"); 
Application["NoOfVisitors"] = _count; 

寫在C#應用程序的文本文件,但我得到一個錯誤:

The process cannot access the file 'path' because it is being used by another process.

我的錯誤是什麼?

回答

6

您試圖打開文件兩次;您的第一個using語句會創建一個未使用的FileStream,但會鎖定該文件,因此第二個using會失敗。

只需刪除您的第一個using行,它應該都可以正常工作。

但是,我建議用File.WriteAllText替換所有這些,那麼在代碼中就不會使用它,這會更簡單。

var dir = Server.MapPath("~\\count"); 
var file = Path.Combine(dir, "count.txt"); 

Directory.CreateDirectory(dir); 
File.WriteAllText(file, "101"); 

var _count = File.ReadAllText(file); 
Application["NoOfVisitors"] = _count; 
+0

我需要重新啓動visual studio或系統? – 2014-10-04 07:37:56

+0

重新啓動你的電腦肯定會修復它(除非它是你的應用程序的早期部分鎖定它),但否則它取決於它鎖定的是什麼。 – 2014-10-04 07:51:22

+0

我嘗試了兩個選項,但仍面臨相同的問題.... – 2014-10-04 08:16:30