Damon Bauer
Damon Bauer

Reputation: 2726

C# File Caching

I've got a class with a method "GetNewsFeed", that when a page is requested:

I am not very well versed with C#, so I'm trying to cobble together a few sources. I believe I am close, but I'm unable to get the files to refresh every 30 minutes if needed (I'm not getting any compliation errors or anything). Any help would be appreciated.

public static string GetNewsFeed(string url, string fileName)
{
    // Set the path to the cache file
    String filePath = HttpContext.Current.Server.MapPath("/cachefeed/" + fileName + ".txt");
    string fileContents = "";

    // If the file exists & is less than 30 minutes old, read from the file.
    if (File.Exists(filePath) && (File.GetLastWriteTime(filePath) > DateTime.Now.AddMinutes(-30)))
    {
        fileContents = File.ReadAllText(filePath);
    }

    else
    {
        try
        {
            // If the file is older than 30 minutes, go out and download a fresh copy
            using (var client = new WebClient())
            {
                // Delete and write the file again
                fileContents = client.DownloadString(url);
                File.Delete(filePath);
                File.WriteAllText(filePath, fileContents);
            }
        }

        catch (Exception)
        {
            if (File.Exists(filePath))
            {
                fileContents = File.ReadAllText(filePath);
            }
        }
    }

    return fileContents;
}

Finally, I've got some code elsewhere that will read these text files and manipulate their contents onto the page. I don't have any issues with this.

Upvotes: 1

Views: 2829

Answers (2)

Damon Bauer
Damon Bauer

Reputation: 2726

I added a throw to my catch and believe it or not, one of the URL's I was passing into my method was invalid. So yes, the culprit in my code was the catch statement.

I fixed this and all is working properly.

Thanks for the tips everyone.

Upvotes: 0

Captain Skyhawk
Captain Skyhawk

Reputation: 3500

Odds are, you're catching an exception in the else block and it's only returning the fileContents. Try putting a breakpoint in the exception block to see what is going on.

You'll need to change it to:

 catch( Exception e )

in order to get this information.

Also, you don't need this:

            File.Delete(filePath);

The WriteAllText method will overwrite the file that is already there. Try removing that line and check your directory permissions.

You may also want to change

 (File.GetLastWriteTime(filePath) > DateTime.Now.AddMinutes(-30)))

to

 (DateTime.Now - File.GetLastWriteTime(filePath)).TotalMinutes > 30

Upvotes: 4

Related Questions