- Home /
Serialize XML File Delete and CreateNew
Hi! I want to save XML and firstly if this XML exists I want to delete it.
So I do:
if (File.Exists (path)) {
Debug.Log("DELETING : ");
File.WriteAllText(path,string.Empty);
}
var serializer = new XmlSerializer(typeof(DronesSerialize));
using (var stream = new FileStream(path, FileMode.CreateNew)) {
serializer.Serialize (stream, this);
Debug.Log("WRITING : ");
}
And unfortunetly it doesnt work, my XML just keep getting bigger, it is appending to file instead of deleting and creating new one.
I checked only File.Delete without FileMode.createNew and then it successfully deleted File. However when it supposed to delete file if exists and then create new file, it appends content to existing one.
Please help, I don't know what cause this issue.
Answer by CaKeMeaT · Jun 23, 2015 at 11:57 PM
FileMode.Create is what I use, does what you ask.
Create Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
Well, thanks for your answer, however File$$anonymous$$ode.Create doesnt work either If exists it add the content to existing file
never $$anonymous$$d, I didn't reset the collection which I was serializing...
Answer by kmgr · Jun 24, 2015 at 10:57 AM
From MSDN:
"File.Create(string) Creates or overwrites a file in the specified path."
You don't need to manually delete the file, or set file mode. Simple File.Create() will overwrite the file if it exists.