The program crashes after trying to use a newly created file. WITH#

So here is my code

if (!File.Exists(pathName))
{
    File.Create(pathName);
}
StreamWriter outputFile = new StreamWriter(pathName,true);

But whenever I run the program, the first time a path with a file is created. However, as soon as I get to the StreamWriter line, my program will crash because it says my fie is being used by another process. Is there something that I am missing between the File.Create and StreamWriter instructions?

+3
source share
4 answers

File.Create does not just create a file - it also opens it for reading and writing. Thus, the file is really used when you try to create StreamWriter: in your own process.

StreamWriter , pathName, , File.Exists :

using (var writer = new StreamWriter(pathName, true))
{
   // ...
}

MSDN:

StreamWriter ()

StreamWriter [...]. , , . , .

+6

, File.Create FileWriter, . . File.Open, , :

var outputFile = new StreamWriter(File.Open(pathName, FileMode.OpenOrCreate));
+2

File.Create .

:

File.Create(pathName).Close();

.

:

using (var file = File.Create(pathName)) {
   // use the file here
   // it will be closed when leaving the using block
}

Also: Why do you create a file that you create 2 lines in your code? the StreamWriter constructor (with append = true) will create or add a file if it does not exist.

+1
source

File.Create returns a FileStream. Why don't you save this and pass it to the StreamWriter constructor instead of passing the path name?

0
source

Source: https://habr.com/ru/post/1747209/


All Articles