Gergő Gutyina
Gergő Gutyina

Reputation: 153

c# can't write to file after creating it

My problem is really simple. I create a file, and I can't write to it. BUT if I close the program then re-open when the file is created, it doesn't throw any exceptions. I think when the File.Create method runs, the program locks it. path is just a location of a txt file. When I try to delete the file manually, it says my program using it.

if (!File.Exists(path)) File.Create(path);

try
{
    File.WriteAllLines(path, new string[] {"hi"});
}
catch(IOException)
{
    Console.WriteLine(ex.ToString());
}

Upvotes: 0

Views: 2019

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

You don't want

File.Create(path);

Since it creates FileStream which put an exlusive lock on the file. All you need is File.WriteAllLines:

try
{
    File.WriteAllLines(path, new string[] {"hi"});
}
catch (IOException ex)
{
    Console.WriteLine(ex.ToString());
}

In case you want to be sure that all subdirectories within path are created you should create the directory, not the file:

try
{
    Directory.CreateDirectory(Path.GetDirectoryName(path));

    File.WriteAllLines(path, new string[] {"hi"});
}
catch (IOException ex)
{
    Console.WriteLine(ex.ToString());
}

Upvotes: 3

Related Questions