【问题标题】:Open a file that is being used by another process [duplicate]打开另一个进程正在使用的文件[重复]
【发布时间】:2013-12-17 21:34:12
【问题描述】:

我正在尝试从文件夹中读取文本文件,但当前该文件正在被另一个进程访问。因此,我得到一个例外,即“...文件正在被另一个进程访问”。

我正在使用以下代码

class program
{
  static void Main(string[] args) 
  {   
    string lFileData = string.Empty; 
    try 
    { 
        if (args.Count() > 0) 
            lFileData = ReadLogFile(args[0]); 

        Console.WriteLine("{0}", lFileData); 

    } 
    catch(Exception ex) 
    { 
        Console.WriteLine("{0}", ex.Message.ToString()); 
    } 
    Console.ReadLine(); 
  }

  public static string ReadLogFile(string sFileLocation) 
  { 
    string lResult = string.Empty; 
    var inStream = new FileStream(sFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read);            
    using (var reader = new StreamReader(inStream)) 
    { 
       lResult= reader.ReadToEnd(); 
    } 
    return lResult; 
  }
}

但是当我们通过记事本打开同一个文件时,即使文件正在被另一个进程访问,也会显示文本文件的内容。

我们也想做同样的事情——读取文件的内容而不做任何修改。 因此我尝试了这个:

 var inStream = new FileStream(sFileLocation, FileMode.Open, FileAccess.Read, FileShare.Read); 

但是,即便如此,我们也会遇到同样的异常。

谁能帮忙解决这个问题?

【问题讨论】:

  • 您能提供演示问题的代码或步骤吗?我不清楚是如何重现这个问题的。
  • 似乎在这里stackoverflow.com/questions/9759697/… 讨论了同样的问题
  • 使用FileShare.ReadWrite?
  • 你需要有一个被其他应用程序独占访问的文件,Post运行上面的代码,cmdline参数ash文件路径被其他应用程序独占访问。
  • @Matthew Watson,我们正在使用这个 FileShare Enum,它不起作用,然后我们将其更改为 FileShare.Read。

标签: c# .net filestream


【解决方案1】:

记事本可能正在做的是制作文件的副本,然后从中读取。如果您尝试在记事本中保存,它会给您您遇到的错误。

因此,解决此问题的一种方法是制作文件的副本 (File.Copy()) 并打开它。

【讨论】:

    【解决方案2】:
    System.IO.FileStream fs = new System.IO.FileStream(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.FileShare.ReadWrite);  
    
    System.IO.StreamReader sr = new System.IO.StreamReader(fs);  
    
    List<String> lst = new List<string>();  
    
    while (!sr.EndOfStream)  
         lst.Add(sr.ReadLine());  
    

    通知更改为 ReadWrite。

    http://msdn.microsoft.com/en-us/library/system.io.fileshare(v=vs.110).aspx

    【讨论】:

      【解决方案3】:
      using (FileStream fs = 
          new FileStream(sFileLocation,
              FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
      

      您的文件可能被写锁定,因此请尝试使用FileShare.ReadWrite

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-12
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多