我有以下方法(下面),你可以看到它將一個對象序列化爲一個XML文件。我遇到的主要問題是我想讓函數覆蓋文件(如果存在)。 我知道我可以先刪除文件,如果它確實存在,但這也意味着我可能會導致一些錯誤拖入我的應用程序。所以我希望它是一個全部或沒有,覆蓋的方法...C#序列化到文件,覆蓋,如果存在
這是關於如何完成這一功能的任何想法?
/// <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);
}
}
我認爲它會工作 - 真棒!和ty – 2010-01-14 13:31:16