I can't understand where problem is, despite the fact, that this code pretty easy.
I have such function:
public void WriteToDoc(string path)
{
XDocument doc = new XDocument(new XElement("General parameters",
new XElement("num_path", num_path.Text),
new XElement("Gen_Peroid", Gen_Peroid.Text),
new XElement("Alg_Perioad", Alg_Perioad.Text))
);
doc.Save(path); // here he gives that exception
}
num_path.Text
, Gen_Peroid.Text
and Alg_Perioad.Text
are string
.
This is how I use this function:
File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml");
WriteToDoc(@"C:\ProgramData\RadiolocationQ\Q.xml");
It creates file, but nothing was written in that file. So the exact error System.IO.IOException
error, The process cannot access the file because it is being used by another process. How is it possible to get such error?
XDocument.Save will create a file if one doesnt exist. There is no need for
File.Create()
File.Create()
is not closing, It is locking the file on you.As the other answers state, you are not closing your output file. The proper way of saving XML files using LinqToXML is:
This releases the file & stream. You can omit the
XmlWriterSettings
if not needed.You are the process that has it open!
Don't call
File.Create
first - it leaves the file stream open, and you can't write over the file.XDocument.Save
will create the file - you don't have to:Try
Edit: Reinhards answer is better. My is just closing the File.Create() stream, which locks the File, but there is no need for.