![](/img/trans.png)
[英]The process cannot access the file 'D:.txt' because it is being used by another process in c#
[英]The process cannot access the file 'C:\file.txt' because it is being used by another process
我正在嘗試在我的程序上記錄每個方法,我在IIS服務器上部署了應用程序,用戶只是打電話給我並說電子郵件功能不起作用所以我需要基本上運行應用程序但將每一步記錄到一個txt文件中。
我宣布以下是全球價值:
StreamWriter writer = new StreamWriter("C:\\file.txt");
然后我在我的代碼中使用它如下所示:
Method 1
{
if (file1.HasFile)
{
writer.WriteLine("Has File");
}
}
方法2
private Boolean InsertUpdateData(SqlCommand cmd)
{
writer.WriteLine("Insert Started" + DateTime.Now.ToString());
}
所以在我的情況下方法一個運行正常,它寫入文件,但當它進入第二個方法,我得到的文件已經打開,這是正確的我該如何解決這個問題?
謝謝
全球價值 - 在頂部宣布
namespace WorkOrderManagement
{
public partial class CreateWorkOrder : System.Web.UI.Page
{
bool successfull;
string path;
string name;
string content;
string datas;
string ext;
bool affectedrows;
string seasonalsupervisor;
private string sLogFormat;
private string sErrorTime;
StreamWriter writer = new StreamWriter("C:\\file.txt");
我真的建議你放棄使用全局變量來表示流然后嘗試在不同方法中使用它的想法。 這在桌面應用程序中很簡單,但在ASP.NET應用程序中要復雜得多。
有一些簡單的替代方法可以自動寫入您的日志文本並保持文件解鎖。
例如,您可以使用這樣的方法
public static class Log
{
public static string _file = "log.txt";
public static object _locked = new object();
public static void AppendToLog(string text)
{
lock(_locked)
{
string path = Server.MapPath("~/APP_DATA");
File.AppendAllText(Path.Combine(path, _file), text + Environment.NewLine);
}
}
}
現在您可以調用日志寫入
Log.AppendToLog("My message");
我想在這里強調兩件重要的事情。 首先,我不寫在服務器的根驅動器中。 當您在沒有權限使用站點根目錄之外的任何服務器的情況下部署ASP.NET應用程序時,這是一種不好的做法,並且始終是問題的根源。 因此,ASP.NET系統在您的站點根目錄下定義一個名為APP_DATA的特定文件夾,您的應用程序應具有讀/寫權限。 要注意的第二點是使用lock關鍵字。 這在像ASP.NET這樣的環境中是必要的,其中兩個用戶可以到達需要寫入公共日志文件的代碼點。 正如MSDN解釋的那樣
lock關鍵字確保一個線程不進入代碼的關鍵部分,而另一個線程處於臨界區。 如果另一個線程試圖輸入鎖定的代碼,它將等待,阻止,直到該對象被釋放。
您也可以這樣做來關閉文件流
using (StreamWriter writer = new StreamWriter("C:\\file.txt"))
{
//your code here
}
//this automatically closes the stream, and it is more recommended.
寫入文件后關閉流
Method 1
{
if (file1.HasFile)
{
writer.WriteLine("Has File");
writer.Close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.