簡體   English   中英

在 C# Dot Net, How to handle a exception when you want to de-serialize a xml file?, 但默認情況下該文件不存在

[英]In C# Dot Net, How to handle a exception when you want to de-serialize a xml file?, but by default the file doesn't exists

在 C# Dot Net,當你想反序列化一個 xml 文件時如何處理異常,但默認情況下該文件不存在。 因為您必須運行該程序才能創建一個。

以下是我需要幫助的地方。

public static Compare_Data[] Deserialize()
        {
            Compare_Data[] cm;
            cm = null;
            string path = @"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";
            XmlSerializer xs = new XmlSerializer(typeof(Compare_Data[]));

            if (File.Exists(path))
            {
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    // This will read the XML from the file and create the new instance of Compare_Data.
                    cm = (Compare_Data[])xs.Deserialize(fs);
                    return cm;
                } 
            }
            else
            {
                using (FileStream fs = new FileStream(path, FileMode.Create))
                {
                    xs.Serialize(fs); ///  what to add here ?
                }
            }

            return null;
        }

如果一般,您不希望您的方法有副作用。 在這種情況下,在else分支中創建一個空日志文件可能是不必要的,當有數據要記錄時,應該由單獨的Serialize()方法處理。

您的代碼可以像這樣簡化:

public static Compare_Data[] Deserialize()
{
    const string path = @"C:\Users\XYZ\Desktop\BACKUP_DATA\log.xml";

    if (!File.Exists(path)) 
    {
        // return null or an empty array, depending on how 
        // you want the calling code to handle this.
        return null;
    }

    using (FileStream fs = new FileStream(path, FileMode.Open))
    {
        var xs = new XmlSerializer(typeof(Compare_Data[]));
        return (Compare_Data[])xs.Deserialize(fs);
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM