I am trying to create a file and write in it using C# code below:
string machinename;
// CHECKING IF THE DIRECTORY EXISTS OR NOT -- IF NOT CREATE ONE
if (!Directory.Exists(Application.StartupPath + @"\Settings\"))
Directory.CreateDirectory(Application.StartupPath + @"\Settings\");
// CHECKING IF THE FILE EXISTS OR NOT -- IF NOT CREATE ONE
if (!File.Exists(Application.StartupPath + @"\Settings\info.txt"))
File.CreateText(Application.StartupPath + @"\Settings\info.txt");
// READING THE CONTNET OF THE FILE AND WRITING IT IN A STRING
machinename = File.ReadAllText(Application.StartupPath + @"\Settings\info.txt");
// IF THE CONTENT IS EMPTY THEN WRITE IN THE FILE FOR FURTHUR USE
if (machinename == "")
{
File.WriteAllText(Application.StartupPath + @"\Settings\info.txt", Environment.MachineName);
machinename = Environment.MachineName;
}
// Do Stuff with "machinename"
But I get the following error :
Message = The process cannot access the file because it is being used by another process.
And it throws the exception on this line :
machinename = File.ReadAllText(Application.StartupPath + @"\Settings\info.txt");
Exactly after creating the file.
(This means if the exists but it is empty it can read it and write in it, But it cant create and read from it).
That is because functions ReadAllText
and WriteAllText
use the embedded File.Close()
and by what I see File.CreateText()
does not have it.
Now the question is:
How can I makes sure that the process Closes
the file after creating it?
NOTES:
- No I am not using the file in other places of the code.
- I have read other answers about this particular kind of error in here but it does not answer my question
- The link above mostly uses
StreamWriter
which I don not want to use because my string is not a large one to process and it is easier to use this way.