Writting a xml file

A

Alberto

I have this code to write a xml file:

public void Grabar()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "xml";

sfd.InitialDirectory = Config.Directory;
if (sfd.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sfd.FileName,
FileMode.Create);

XmlTextWriter tw = new XmlTextWriter(sfd.FileName, null);
<=====

tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
....

When I execute the code, it breaks in the selected line. It says that the
file it's been used by another process but the file it's new. I type a new
name in the filedialog form.
Thank you for your help.
 
G

Göran Andersson

Alberto said:
I have this code to write a xml file:

public void Grabar()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "xml";

sfd.InitialDirectory = Config.Directory;
if (sfd.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(sfd.FileName,
FileMode.Create);

XmlTextWriter tw = new XmlTextWriter(sfd.FileName, null);
<=====

tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
....

When I execute the code, it breaks in the selected line. It says that
the file it's been used by another process but the file it's new. I type
a new name in the filedialog form.
Thank you for your help.

You are creating the file in the previous line, but you are not closing
it. Therefore it's your own code that is using the file.

Don't use a FileStream to create the file, let the XmlTextWriter create
it for you instead.
 
M

Martin Honnen

Göran Andersson said:
You are creating the file in the previous line, but you are not closing
it. Therefore it's your own code that is using the file.

Don't use a FileStream to create the file, let the XmlTextWriter create
it for you instead.

Also note that since .NET 2.0 you should use XmlWriter.Create instead of
new XmlTextWriter e.g.
XmlWriterSettings xws = new XmlWriterSettings();
xws.Indent = true;
using (XmlWriter xw = XmlWriter.Create(sfd.FileName, xws))
{
// write stuff here
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top