c#文件缓存

本文关键字:缓存 文件 | 更新日期: 2023-09-27 18:18:27

我有一个类的方法"GetNewsFeed",当一个页面被请求:

  • 检查文件是否存在&它还不到30分钟
    • 如果不存在,读取文件的内容,将内容推送到
    • 如果不存在,转到URL并将该页的内容写入。txt文件,将内容推送到

我不是很精通c#,所以我试图拼凑一些资源。我相信我已经接近了,但是如果需要的话,我无法让文件每30分钟刷新一次(我没有得到任何复杂性错误或任何东西)。如有任何帮助,不胜感激。

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

最后,我在其他地方编写了一些代码,这些代码将读取这些文本文件并将其内容操作到页面上。我对此没有任何意见。

c#文件缓存

很可能,你在else块中捕获了一个异常,它只返回fileContents。试着在异常块中设置一个断点,看看发生了什么。

你需要把它改成:

 catch( Exception e )

,以获得此信息。

同样,你不需要这个:

            File.Delete(filePath);

WriteAllText方法将覆盖已经存在的文件。试着删除那一行,然后检查你的目录权限。

您可能还想更改

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

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

我添加了一个throw到我的catch,信不信由你,其中一个URL的我传递到我的方法是无效的。所以,是的,我代码中的罪魁祸首是catch语句。

我修复了这个,一切正常。

谢谢大家的提示。