ページがリクエストされたときに「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;
}
最後に、これらのテキスト ファイルを読み取り、そのコンテンツをページ上で操作するコードを別の場所に用意しました。私はこれで何の問題もありません。