PRR's way is great. The XmlTextWriter (and all the other stream readers and writers) implement IDisposable, which provides a means to clean up after themselves.
What is happening under the covers:
When you instantiate a new XmlTexWriter with a path as a parameter, it is creating a
FileStream with a
FileAccess of "Write." In windows, that puts a lock on the file for editing, basically, the process that your program is on has an exclusive lock on that file.
It maintains this lock until you call the .Close() method on your stream. If you terminate your program before you release the file, the file will remain locked. Eventually the OS will unlock the file again, but you are unable to write to the file again until that happens, and it doesn't happen quickly.
Fortunately, in it's implementation of the IDisposable interface, in the Dispose() method, this.Close() is called. So, when you do this:
-
using (XmlTextWriter xt = new XmlTextWriter(somePath, null))
-
{
-
-
}
when that code block exits, it automatically calls the .Dispose() method on the object in the using statement. Your stream will close, the process will release the lock on the file.
Sorry for the long explanation, but I feel that it is important to understand what is going on under the covers.