c# – FileMode和FileAccess以及IOException:进程无法访问文件’filename’,因为它正被另一个进程使用

我有一个应用程序A,它生成一个用于跟踪的文本文件.
同时,应用程序B需要读取相同的文本文件并附加到邮件消息中.

但是当应用程序B尝试读取文本文件时,我收到以下错误:

IOException: The process cannot access the file ‘filename’ because it
is being used by another process

有什么建议 ?也许更好地用于FileMode和FileAccess?

申请A.

if (File.Exists(nFile2)) File.Delete(nFile2);
                traceFile2 = File.Open(nFile2, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                if (traceFile2 != null)
                {
                    var twt2 = new TextWriterTraceListener(traceFile2);

                    // http://www.helixoft.com/blog/archives/20
                    try
                    {
                        if (twt2.Writer is StreamWriter)
                        {
                            (twt2.Writer as StreamWriter).AutoFlush = true;
                        }
                    }
                    catch { }

                    var indiceTraceFile2 = Trace.Listeners.Add(twt2);
                    System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());

申请B.

using (FileStream fileStream = File.Open(f, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                    {
                        var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
                        msgMail.Attachments.Add(messageAttachment);
                    }
最佳答案
您需要确保服务和阅读器都非独占地打开日志文件.注意App A的第2行和App B的第1行

申请A:

if (File.Exists(nFile2)) 
    File.Delete(nFile2);
traceFile2 =  new FileStream(nFile2, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
if (traceFile2 != null)
{
    var twt2 = new TextWriterTraceListener(traceFile2);
    // http://www.helixoft.com/blog/archives/20
    try
    {
        if (twt2.Writer is StreamWriter)
        {
            (twt2.Writer as StreamWriter).AutoFlush = true;
        }
    }
    catch { }

    var indiceTraceFile2 = Trace.Listeners.Add(twt2);
    System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());

和申请B:

using (FileStream fileStream = new FileStream(f, FileMode.Open, 
                                                 FileAccess.Read, 
                                                 FileShare.ReadWrite))
{
    var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
    msgMail.Attachments.Add(messageAttachment);
}

转载注明原文:c# – FileMode和FileAccess以及IOException:进程无法访问文件’filename’,因为它正被另一个进程使用 - 代码日志