Search code examples
c#xmlfilestreamfile-permissions

Overwrite existing XML file if it alreadly exists


I am trying to overwrite an existing xml file if it already exists.

I am using the code below to check if the file exists and then overwrite it if it does. The existing file is hidden so I am unhiding it before attempting to overwrite.

The changes are not occuring to the file and the overwriting is not working however.

Here is the code I am using below minus the part where I am writing the new xml data.

if(File.Exists(filePath))
{
     File.SetAttributes(filePath,FileAttributes.Normal);
     FileIOPermission filePermission = 
              new FileIOPermission(FileIOPermissionAccess.AllAccess,filePath);

     FileStream fs = new FileStream(filePath, FileMode.Create);

     XmlWriter w = XmlWriter.Create(fs);
 }

Solution

  • Try writing to the file like this :

    if(File.Exists(filePath))
    {
         File.SetAttributes(filePath,FileAttributes.Normal);
         FileIOPermission filePermission = 
                  new FileIOPermission(FileIOPermissionAccess.AllAccess,filePath);
    
         using(FileStream fs = new FileStream(filePath, FileMode.Create))
         {
             using (XmlWriter w = XmlWriter.Create(fs))
             {
                 w.WriteStartElement("book");
                 w.WriteElementString("price", "19.95");
                 w.WriteEndElement();
                 w.Flush();
             }
         }     
     }