1: public class CachedTextFile
2: {
3: public readonly string FileName;
4: WeakReference wrText;
5: public CachedTextFile(string filename)
6: {
7: this.FileName = filename;
8: }
9:
10: private string ReadFile()
11: {
12: string text = string.Empty;
13: using (StreamReader sr = new StreamReader(FileName))
14: {
15: text = sr.ReadToEnd();
16: }
17: wrText = new WeakReference(text);
18: return text;
19: }
20:
21: public string GetText()
22: {
23: object text = null;
24: //check weak reference
25: if (wrText != null)
26: text = wrText.Target;
27: if (text != null)
28: {
29: //string still in cache
30: return text.ToString();
31: }
32: else
33: {
34: //read from disk
35: return ReadFile();
36: }
37: }
38: }
39:
40:
41: CachedTextFile cacheFile = new CachedTextFile(@"C:\temp\test.txt");
42: // this is the first call hence gets the text from disk, instead of memory/cache
43: Console.WriteLine(cacheFile.GetText());
44: //force garbage collection manually
45: GC.Collect();
46: GC.WaitForPendingFinalizers();
47: //following causes the app to read the file again
48: Console.WriteLine(cacheFile.GetText());