开发者

Gracefully handle loading of XElement from an empty file

开发者 https://www.devze.com 2023-03-23 00:56 出处:网络
I have a use-case where I\'m required to read in some information from an XML file and act on it accordingly. The problem is, this XML file is technically allowed to be empty or full of whitespace and

I have a use-case where I'm required to read in some information from an XML file and act on it accordingly. The problem is, this XML file is technically allowed to be empty or full of whitespace and this means "there's no info, do nothing", any other error should fail hard.

I'm currently thinking about something along the lines of:

    public void Load (string fileName)
    {
        XElement xml;
        try {
            xml = XElement.Load (fileName);
        }
        catch (XmlException e) {
            // Check if the file contains only whitespace here
            // if not, re-throw the exception
        }
        if (xml != null) {
            // Do this only if there wasn't an exception
            doStuff (xml);
        }
   开发者_运维百科     // Run this irrespective if there was any xml or not
        tidyUp ();
    }

Does this pattern seem ok? If so, how do people recommend implementing the check for if the file contained only whitespace inside the catch block? Google only throws up checks for if a string is whitespace...

Cheers muchly,

Graham


Well, the easiest way is probably to make sure it isn't whitespace in the first place, by reading the entire file into a string first (I'm assuming it isn't too huge):

public void Load (string fileName)
{
    var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    var reader = new StreamReader(stream, Encoding.UTF8, true);
    var xmlString = reader.ReadToEnd();

    if (!string.IsNullOrWhiteSpace(xmlString)) {  // Use (xmlString.Trim().Length == 0) for .NET < 4
        var xml = XElement.Parse(xmlString);    // Exceptions will bubble up
        doStuff(xml);
    }

    tidyUp();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消