簡體   English   中英

IOException:該進程無法訪問文件“文件路徑”,因為它正在被C#控制台應用程序中的另一個進程使用

[英]IOException: The process cannot access the file 'file path' because it is being used by another process in Console Application in C#

我正在運行Console_Application-A,在其中我調用另一個Console_Application-B(在其中我為錯誤/異常創建日志文件)。

但是,當我分別運行Console_Application-B時,它正常工作,但是當我當時運行Console_Application-A時,當應用程序需要在日志文件中寫入錯誤時,我會收到異常消息。(Error.txt)。

IOException:該進程無法訪問文件'Error.txt',因為它正在被另一個進程使用

請在這個問題上指導我。

寫入錯誤日志的代碼

public static bool IsFileLocked(FileInfo file)
{
 FileStream stream = null;
 try
 {
 stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
 }
 catch (IOException)
 {
  return true;
 }
 finally
 {
  if (stream != null)
  stream.Close();
  }
  return false;
 }

catch (Exception e)
{
    string filePath =Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Error.txt";

FileInfo FInfo = new FileInfo(filePath);
var FileState = IsFileLocked(FInfo);

while (FileState){
FileState = IsFileLocked(FInfo);
}
if (!FileState){
using (StreamWriter writer = new StreamWriter(filePath, true))
{
 writer.WriteLine("Message :" + e.Message + "<br/>" + Environment.NewLine + "StackTrace :" + e.StackTrace +"" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
 writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
writer.Dispose();
}
}
}

不需要先檢查文件是否已鎖定然后再訪問它,因為在檢查和訪問之間,某些其他進程可能仍會鎖定文件。

using System;
using System.IO;

class DirAppend
{
    public static void Main()
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log("Test1", w);
            Log("Test2", w);
        }

        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog(r);
        }
    }

    public static void Log(string logMessage, TextWriter w)
    {
        w.Write("\r\nLog Entry : ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
            DateTime.Now.ToLongDateString());
        w.WriteLine("  :");
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine ("-------------------------------");
    }

    public static void DumpLog(StreamReader r)
    {
        string line;
        while ((line = r.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}

來源-https: //msdn.microsoft.com/zh-cn/library/3zc0w663(v=vs.110).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM