简体   繁体   中英

If xml file does not exist

I am using ASP.NET C# and have written a page using the XmlDataSource tool to read an xml file and display the data in a GridView. Everything is great when the file is there. However, the xml file is generated every hour and if you happen to connect to the page while the file is being updated (takes about 2 minutes) an error is displayed (because the file is not there). As I am using the built-in tools to connect and read the xml, is there code that I can use to check if the file exists and, if it does not, open the page without the file.

I can see that there is code to do an if exists, however I can not seem to figure out the part "what to do?" to ignore the XMLDataSource tool. Perhaps I can make a label appear that says to come back in a few minutes, but how do I get it to ignore the data reader?

if (!File.Exists(filename))
{
     // what to do?
}  

If you try to use File.Exists in this way, you're going to be disappointed.

Let's say you have code that works in the simplest way:

if (!File.Exists(filename))
{
    // Tell user that file isn't there.
}
else
{
    // The file exists, so now go party on it.
    DoSomething(filename);
}

So your program determines that the file exists. But before DoSomething is called, the process that creates the file opens it for exclusive access. Your DoSomething method is then going to fail. So your check for the file's existence was irrelevant.

Yes, it's a very small window. I can tell you from experience that things do indeed happen within those very small windows. I've been bitten by code similar to that above.

I strongly suggest that you write your code so that it handles the FileNotFoundException (or whatever exception) that is thrown when the file doesn't exist. For example:

try
{
    DoSomething(filename);
    // now format the page as normal
}
catch (FileNotFoundException)
{
    // notify user that the file wasn't found
}

Done this way, no other process can pull the rug out from under you. You know that the file is there because you have it open.

Here is my solution. I change variable names to protect the innocent. Many thanks to Jim Mischel...

protected void Page_Load(object sender, EventArgs e)
{
    string xmlFile = Server.MapPath("~/App_Data/file.xml");

    try
    {
        XmlDataSource1.DataFile = xmlFile;
        XmlDataSource1.GetXmlDocument();
    }
    catch (Exception ex)
    {
        lblErrorMessage.Visible = true;
        gridView1.Visible = false;
        formView1.Visible = false;
    }
}

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