Skip to main content
 首页 » 编程设计

C# 文件缓存

2024年02月13日15mengfanrong

我有一个带有“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; 
} 

最后,我在其他地方得到了一些代码,可以读取这些文本文件并将它们的内容操作到页面上。我对此没有任何问题。

请您参考如下方法:

很有可能,您在 else block 中捕获了一个异常,它只返回文件内容。尝试在异常 block 中放置一个断点以查看发生了什么。

您需要将其更改为:

 catch( Exception e ) 

为了得到这些信息。

另外,你不需要这个:

            File.Delete(filePath); 

WriteAllText 方法将覆盖已经存在的文件。尝试删除该行并检查您的目录权限。

你可能还想改变

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

到

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