2010-12-12 40 views
0
public static void WriteLine(string text) 
    { 
     StreamWriter log; 

     if (!File.Exists(Filename)) 
     { 
      log = new StreamWriter(Filename); 
     } 
     else 
     { 
      log = File.AppendText(Filename); 
     } 

while this method is processed,other process also call this method。 “文件已被其他进程访问”会发生错误。如何通过等待先前的过程完成来解决这个问题。c#如果该文件被其他进程处理,如何访问文件?

回答

1

这两个进程都需要创建一个FileStream,它们指定了一个FileShare模式的写入。然后,您也可以放弃测试文件是否存在,并使用Append FileMode。

2

我想操作系统想等到文件句柄可以自由使用然后写入文件。在这种情况下,您应该尝试获取文件句柄,捕获异常,并且如果异常是因为该文件被另一个进程访问,那么请稍等片刻,然后重试。

public static void WriteLine(string text) 
     { 
      bool success = false; 
      while (!success) 
      { 

       try 
       { 
        using (var fs = new FileStream(Filename, FileMode.Append)) 
        { 
         // todo: write to stream here 

         success = true; 
        } 
       } 
       catch (IOException) 
       { 
        int errno = Marshal.GetLastWin32Error(); 
        if(errno != 32) // ERROR_SHARING_VIOLATION 
        { 
         // we only want to handle the 
         // "The process cannot access the file because it is being used by another process" 
         // exception and try again, all other exceptions should not be caught here 
         throw; 
        } 

       Thread.Sleep(100); 
       } 
      } 

     } 
+1

如果您的进程是唯一访问该文件的进程,那么您也可以使用锁定。但是使用上面的代码会更节省,因为它甚至可以处理多个进程的文件访问。 – flayn 2010-12-12 11:19:41

相关问题