繁体   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