IOException未处理 - “无法访问文件,因为它正被另一个进程使用”

时间:2014-12-09 04:36:47

标签: c# file ioexception

每次尝试在创建文件后读取文件时都会出现此错误。要遵循这个过程:

  • 使用

    创建文件
    File.Create(filename);
    
  • 然后我尝试使用以下方法读取该文件:

    StreamReader rdr = new StreamReader(filename); //error catches here
    

    我收到错误:

      

    该进程无法访问文件'(filename)',因为它正由另一个进程使用。

这是因为我在创建文件后还没有关闭文件吗?我怎么做? File.Close(fileName);有效吗?

3 个答案:

答案 0 :(得分:1)

是的,你必须先关闭文件。

来自the MSDN article

  

此方法创建的FileStream对象具有默认的FileShare   无价值;没有其他进程或代码可以访问创建的文件   直到原始文件句柄关闭。

因此,您必须分配File.Create的返回值,即FileStream,然后关闭所述流的句柄以访问该文件。

答案 1 :(得分:1)

File.create可能会返回文件流。使用

file.create().close();

答案 2 :(得分:0)

是的,因为你打开了文件,如果再次打开,它会抛出异常。你应该这样使用它:

 using (FileStream fs = File.Create(path))
    {
    }
    using (StreamReader sr = new StreamReader(path)) 
    {
    }