tags:

views:

319

answers:

3

In my code, I have these lines:

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
XmlWriter writer = XmlWriter.Create(filename, writerSettings);
document.Save(writer);

This works fine when filename does not exist. But when it does, I get this error (on the 3rd line, not the 4th):

System.IO.IOException: Sharing violation on path [the file path]

I want to overwrite the file if it already exists. How do I do this?

A: 

Try using the overload of XmlWriter.Create that accepts a Stream, and pass in a FileStream from File.Create(filename)...

nitzmahone
+1  A: 

The problem isn't that the file exists, but that it is in use by a different program (or your own program). If it was simply that the file existed it would be overwritten and cause no exception.

If it's your program that has created the file that exists already, it's likely that you haven't disposed properly the object that created the file, so the file is still open.

Guffa
+1  A: 

If you look carefully at the IOException, it says that it's a "sharing violation". This means that while you are trying to access this file, another program is using it. Usually, it's not much of a problem with reading, but with writing to files this can happen quite a lot. You should:

  • Try to find out if some other program is using this file, what the program is, and why it's doing so. It's possible that some programs (especially those written in languages without good garbage handling capabilities) were accessing the file and then did not close the IO stream, thus locking up the file. There are also some utilities (if my memory serves me correctly) that allow you to see what processes are using a certain file - just google it.
  • There's a possibility that when you were debugging your program, you may have killed the process or something (I do that sometimes), and the IO stream may have not been closed. For this, the easiest fix (as far as I know) is just a reboot.
  • Alternatively, the issue may be coming from your own code. However, as you're writing in C#, and garbage collection, along with the IO capabilities, usually prevent such problems, you might have forgotten to close a file stream somewhere. I do this sometimes, and it takes quite a while to find the location of the bug, even though the fix is nearly instant. If you step through your program and utilize watches to keep track of your IO operations, it should be relatively simple to find such a bug.

Good luck!

Maxim Zaslavsky