System.IO.IOException error, can't get access

2019-07-13 11:29发布

问题:

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?

回答1:

As the other answers state, you are not closing your output file. The proper way of saving XML files using LinqToXML is:

System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings();
xws.Indent = true;
xws.IndentChars = "\t";

FileStream fsConfig = new FileStream(path, FileMode.Create);
using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(fsConfig, xws))
{
       doc.Save(xw);
}
fsConfig.Close();

This releases the file & stream. You can omit the XmlWriterSettings if not needed.



回答2:

Try

System.IO.File.Create(@"C:\ProgramData\RadiolocationQ\Q.xml").Close();

Edit: Reinhards answer is better. My is just closing the File.Create() stream, which locks the File, but there is no need for.



回答3:

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:

Serialize this XDocument to a file, overwriting an existing file, if it exists.



回答4:

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.