- Home /
Writing to a file which i just created.
Hello i have a problem, i created a directory and a file in that directory. And i want to save something to this file but i got a error: IOException: Sharing violation on path. This is my code:
path_md=System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
path_md = path_md + "/Gladiator";
Directory.CreateDirectory(path_md);
path_md = path_md + "/character_stats.txt";
File.Create(path_md);
lines = new string[3]; I declared a array above with that: public string[] lines;
lines[0] = "dadad";
lines[1] = "adasdasd";
lines[2] = "adadadadadadad";
File.WriteAllLines(path_md,lines);
Debug.Log("after");
The folder and a file are created but i can't write something to it:( Should i close that file or something, i just don't know, instead of a File.WriteAllLines i tried using a StreamWrite but i got the same error:(
This question is very similar to this one which was asked just a few days ago. Where do you get the idea from that you have to create the file before you can write to it? "File.Create" opens the file for writing. However you never close the file s$$anonymous$$m that is returned by this method. That's why you get a sharing violation. The File.Create call is completely pointless. "WriteAllLines" does create the file if it doesn't exist.
Answer by zapextreme · Jan 09, 2019 at 03:22 PM
You should be able to use StreamWriter For that.
using(StreamWriter sw = new StreamWriter(fileName, true, System.Text.Encoding.Default))
{
string path_md=System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
path_md = path_md + "/Gladiator";
Directory.CreateDirectory(path_md);
string [] lines = new string[3];
lines[0] = "dadad";
lines[1] = "adasdasd";
lines[2] = "adadadadadadad";
for(int i = 0; i < lines.Length; i++){
sw.WriteLine(lines[i]);
}
Debug.Log("after");
}
It doesn't work for me:( It created a folder in Documents but didn't created a file. A replace a fileName with "/character_stats.txt".
using (FileStream fs = File.Create(directoryTarget + "/name.extension"))
{
//Do fs stuff here
}
It's pretty pointless to create the directory you want to store the file in after you created the file (aka inside the using block).