C#序列化到文件,如果存在则覆盖 [英] C# Serialization to file, overwrite if exists

查看:735
本文介绍了C#序列化到文件,如果存在则覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的方法(如下图),你可以看到它的序列化对象到XML文件。我遇到的主要问题是我希望得到的功能覆盖文件(如果存在)。
我知道我可以先删除该文件,如果它确实存在,但这也意味着我可能会诱发一些错误拖入我的申请。所以,我希望它全有或全无,覆盖方法...



下面是函数,这是如何得来的任何想法?



  ///<总结> 
///序列化对象到XML文件。
///< /总结>
///< PARAM NAME =目标文件>
///对象序列化。
///< /参数>
///< PARAM NAME =输入>
///的对象的类型被传递。
///< /参数>
///< PARAM NAME =文件名>
///该对象应保存的文件名。
///< /参数>
///< PARAM NAME =xsltPath>
///传递一个空,如果不是必需的。
///< /参数>
公共静态无效SerializeToXmlFile(obj对象,类型类型,字符串文件名,字符串xsltPath)
{
变种NS =新XmlSerializerNamespaces();
ns.Add(的String.Empty,的String.Empty);
无功序列化=新的XmlSerializer(类型);

VAR设置=新XmlWriterSettings {缩进= TRUE,IndentChars =\t};使用(VAR W = XmlWriter.Create(文件名,设置))
{




如果(!String.IsNullOrEmpty(xsltPath))
{
w.WriteProcessingInstruction(xml样式表,类型= \文/ xsl\的href = \+ xsltPath +\);

}
serializer.Serialize(W,OBJ,NS);
}
}


解决方案

使用的重载版本的 XmlWriter.Create ,需要一个而不是字符串,并使用 File.Create 以创建/覆盖文件:使用(VAR是W

  = XmlWriter.Create (File.Create(文件名),设置))
...


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.Create that takes a Stream instead of a string, and use File.Create to create/overwrite the file:

using (var w = XmlWriter.Create(File.Create(fileName), settings))
...

这篇关于C#序列化到文件,如果存在则覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆