title: C# Serialization to file, overwrite if exists
body: <p>I have the following method (below), as you can see it serializes an object to an XML file. The main problem I am having is I want to get the function to overwrite a file if it exists. 
  I know I could delete the file first if it does exist, but this would also mean that I might induce some error drag into my application. So I want it an all or nothing, overwrite method...</p>
  
  <p>Here is the function, any ideas on how this can be accomplished?</p>
  
  <pre><code>/// &lt;summary&gt;
      /// Serializes an object to an xml file.
      /// &lt;/summary&gt;
      /// &lt;param name="obj"&gt;
      /// The object to serialize.
      /// &lt;/param&gt;
      /// &lt;param name="type"&gt;
      /// The class type of the object being passed.
      /// &lt;/param&gt;
      /// &lt;param name="fileName"&gt;
      /// The filename where the object should be saved to.
      /// &lt;/param&gt;
      /// &lt;param name="xsltPath"&gt;
      /// Pass a null if not required.
      /// &lt;/param&gt;
      public static void SerializeToXmlFile(object obj, Type type, string fileName, string xsltPath )
      {
          var ns = new XmlSerializerNamespaces();
          ns.Add(String.Empty, String.Empty);
          var serializer = new XmlSerializer(type);
  
          var settings = new XmlWriterSettings {Indent = true, IndentChars = "\t"};
  
  
          using (var w = XmlWriter.Create(fileName,settings))
          {
  
              if (!String.IsNullOrEmpty(xsltPath))
              {
                  w.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + xsltPath + "\"");
  
              }
              serializer.Serialize(w, obj, ns);
          }
      }
  </code></pre>