我有以下方法(如下所示),因为您可以看到它将对象序列化为XML文件.我遇到的主要问题是我想让函数覆盖文件(如果存在).我知道如果它确实存在,我可以先删除该文件,但这也意味着我可能会在我的应用程序中引发一些错误.所以我想要一个全有或全无,覆盖方法......
这是函数,关于如何实现这一点的任何想法?
/// <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);
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*tad 14
使用XmlWriter.Create带有Stream而不是字符串的重载版本,并使用File.Create创建/覆盖文件:
using (var w = XmlWriter.Create(File.Create(fileName), settings))
...
Run Code Online (Sandbox Code Playgroud)