0

i read the file, when Form loads

string line;
if (!File.Exists(dir)) File.Create(dir);
StreamReader reader = new StreamReader(dir);
while ((line = reader.ReadLine()) != null)
{ /* do something */}
reader.Close();

then I press the button and write something in this file. but in line

System.IO.StreamWriter file = new StreamWriter(dir);

i have an error "file used by another process". why? i close my reader..

leppie
  • 115,091
  • 17
  • 196
  • 297
Konstantin Mokhov
  • 127
  • 1
  • 3
  • 10
  • 1
    Check this link: http://stackoverflow.com/questions/2781357/file-being-used-by-another-process-after-using-file-create – noobob Apr 09 '14 at 10:19
  • 1
    The file is open because File.Create() creates a FileStream. Next you create a StreamReader while the FileStream is still open. Other suggestions: Since you are opening a file, change 'dir' to 'file' (proper variable naming). Also... it doesn't hurt to use line breaks. – TimothyP Apr 09 '14 at 10:25
  • Use File.Open. You can set the "mode" to create the file if it doesn't exist – user3036342 Apr 09 '14 at 10:27

2 Answers2

4

File.Create opens the file and returns you FileStream. Try:

using (var fs = File.Open(dir, FileMode.OpenOrCreate))
{
    using (var reader = new StreamReader(fs))
    {
        while ((line = reader.ReadLine()) != null)
        { /* do something */}
    }
}

EDIT

You can also do

if (!File.Exists(dir)) File.Create(dir).Close();

to make sure stream is closed

dkozl
  • 32,814
  • 8
  • 87
  • 89
2

These 2 lines conflict:

 if (!File.Exists(dir)) File.Create(dir);
 StreamReader reader = new StreamReader(dir);

because File.Create() creates a new file and keeps it open. Therefore blocking the opening of the file for the StreamReader.

On the API level, File.Create() does not what you think. It is very different from Directory.Create().

But functionally your code makes no sense either, why would you create a new file just before reading it? It will always be empty.

Just use

if (File.Exitst(dir))
{
  var lines = System.IO.File.ReadLines(dir);
  foreach(string line in lines) {  /* do something */ }
}
H H
  • 263,252
  • 30
  • 330
  • 514