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…
Here is the function, any ideas on how this can be accomplished?
/// <summary>
/// Serializes an object to an xml file.
/// </summary>
/// <param name="obj">
/// The object to serialize.
/// </param>
/// <param name="type">
/// The class type of the object being passed.
/// </param>
/// <param name="fileName">
/// The filename where the object should be saved to.
/// </param>
/// <param name="xsltPath">
/// Pass a null if not required.
/// </param>
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);
}
}
Use the overloaded version of the
XmlWriter.Createthat takes aStreaminstead of a string, and useFile.Createto create/overwrite the file: