1

I am getting this error every time I try to read a file after it is being created. To follow the process:

  • The file is created using

    File.Create(filename);
    
  • I then attempt to read that file, using:

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

    I get the error:

    The process cannot access the file '(filename)' because it is being used by another process.

Is this occurring because I haven't closed the file after creating it? How do I do that? Does File.Close(fileName); work?

Ben
  • 2,433
  • 5
  • 39
  • 69
  • You cannot read anything from newly created file, because that file contains nothing. In general, you can read something from the file which has been written. What do you want to do? – Fumu 7 Dec 09 '14 at 04:46
  • @Fumu7: That is not a root cause making error. This error occurs because the stream created by `File.Create(filename)` is not closed before calling `StreamReader rdr = new StreamReader(filename)` – Tu Tran Dec 09 '14 at 04:54
  • 1
    It looks ridiculous to me for reading data from newly created file. Ben may not want to know 'How to read data from newly created file' but to know 'How to open file adn read data from that' or 'How to create a file and write data to that'. – Fumu 7 Dec 09 '14 at 05:06

3 Answers3

1

Yes, you have to close the file first.

From the MSDN article:

The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.

So you have to assign the return of File.Create, which is a FileStream, then close the handle to said stream in order to access the file.

Reticulated Spline
  • 1,892
  • 1
  • 18
  • 20
  • Do you know the correct syntax for this? So far `File.Create(filename).Close()` is the best I have received so far, but I'm unsure of it's efficacy. – Ben Dec 09 '14 at 05:22
  • That works just fine if your intention is to create a a file and do nothing with it. If you want to do something with it, you can use a `using` block as in the example in the link I provided. – Reticulated Spline Dec 09 '14 at 12:31
1

File.create probably returns filestream. Use

file.create().close();
Ben
  • 2,433
  • 5
  • 39
  • 69
koder
  • 887
  • 9
  • 29
0

yeah,it's because you have opened the file,if open again,it will throw the exception.You should use it like this:

 using (FileStream fs = File.Create(path))
    {
    }
    using (StreamReader sr = new StreamReader(path)) 
    {
    }
Phenix_yu
  • 294
  • 2
  • 5