views:

156

answers:

2

Hi, I'm trying to use the XmlTextWriter class in C# but it only works if I give the complete path to the file (as in "C:\file.xml"). If I try to use relative path (as in "file.xml"), it creates the file (in the same folder that contais the cs file) but it doesn't show any contents. Is there any property in the project tree in VS I have to set so that the file is updated everytime I run the program?

Some code to help:

If I do:

XmlTextWriter f = new XmlTextWriter("C:/file.xml", null);

it works.

But if I try to use a file that is included in the project ,like this:

XmlTextWriter f = new XmlTextWriter("file.xml", null);

it doesn't work. The file remains empty.

Thnaks in advance.

+3  A: 

It is your responsibility to provide the XMLWriter with a valid file name including the path. This file path can be relative or absolute. The thing is that relative path will work against whatever the current directory will be in at the RUNTIME not what you would expect it to be looking at the source in the designer.

In particular if you give just the filename - no path, the file with the specified name will probably be created right next to your .exe file

mfeingold
Turns out it does create the file next to the .exe file. I have to give the full path to the file.
thiagobrandam
A: 

It sounds like the file stream that is internal to the writer is not being flushed to disk. This will happen automatically when the internal stream reaches a certain size, but I don't think there are any guarantees as to when this happens, or how much data is written to disk. I recommend calling Close() or Dispose() on the writer when you are done using it and want to ensure that its contents are written to disk.

Also, please take note of the following suggestions.

Create the writer using XmlWriter.Create and place it in a using block.

using (XmlWriter writer = XmlWriter.Create(filename))
{ /* code that uses writer */ }

This allows a bit more flexiblity in the creation of the text writer as you can pass XmlReaderSettings if need be. Also, the using block takes care of the close/dispose call when you're done using the writer.

If you are having problems with the contents of the file being overwritten, use the construction overload that accepts a Stream.

using (XmlWriter writer = XmlWriter.Create(File.Open(filename, FileMode.Open))
{ /* code that uses writer */ }

This gives you a bit more control over how clashes in filenames will be handled.

Steve Guidi
Thanks Steve , I follow your suggestions.
thiagobrandam