Can't write to file immediately after creation

3.9k views Asked by At

In the following code:

if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat"))
{
    File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}
else
{
    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat");
    File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", FileAttributes.Hidden);
    File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);
}

for some reason, the first time this code is run, it creates the file just fine, but does not write to it, and it will not until i exit the app, and re-run it. the 2nd, 3rd, and so on runs work just fine, its just the initial that's screwy. any ideas? file names and directories are random since i was just testing something so you should be able to change those to whatever you want if you're testing something. Thanks in advance

4

There are 4 answers

0
Piotr Auguscik On

File.Create is returning you stream to file you might want to close it before you try to reopen it again.

1
linkerro On

Skip creating the file, the AppendAllText method creates it anyway if it's not there. I'm guessing the file.create might leave a file lock or file handle open.

0
AudioBubble On

File.AppendAllText() will create the file if it does not already exist, so you could just do:

File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);         
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", FileAttributes.Hidden); 

See if that helps :)

0
Peter PAD On

You should put .Close() after File.Create

File.Create(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat").Close();

Read more at MSDN File.Create

or You can do this

File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", temp);         
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/data.dat", FileAttributes.Hidden);

Read more at MSDN File.WriteAllText