简体   繁体   中英

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

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. because you have to run the program to create one.

Below is the area where I need Help.

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;
        }

If general, you don't want your methods to have side effects. In this case, creating an empty log file in the else branch is probably unnecessary and should be handled by a separate Serialize() method when there is data to be logged.

Your code could be simplified something like this:

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);
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM