forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IsolatedStorageImageCache.cs
109 lines (97 loc) · 3.58 KB
/
IsolatedStorageImageCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.IsolatedStorage;
using System.Reflection;
namespace Gravatar
{
internal class IsolatedStorageImageCache : IImageCache
{
public static IsolatedStorageFile GetIsolatedStorageFile()
{
return IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
}
public void DeleteCachedFile(string imageFileName)
{
var isolatedStorage = GetIsolatedStorageFile();
if (isolatedStorage.GetFileNames(imageFileName).Length != 0)
{
isolatedStorage.DeleteFile(imageFileName);
}
}
public void ClearCache()
{
foreach (var gravatarFileName in GetIsolatedStorageFile().GetFileNames("*.png"))
GetIsolatedStorageFile().DeleteFile(gravatarFileName);
}
public bool FileIsCached(string imageFileName)
{
return GetIsolatedStorageFile().GetFileNames(imageFileName).Length != 0;
}
public bool FileIsExpired(string imageFileName, int cacheDays)
{
// Very very very ugly function to determine lastwritetime of file in isolated storage
if (cacheDays == 0)
return false;
try
{
var propertyInfo = GetIsolatedStorageFile().GetType().GetField("m_RootDir",
BindingFlags.NonPublic | BindingFlags.Instance);
if (propertyInfo != null)
{
var rootDir = propertyInfo.GetValue(GetIsolatedStorageFile()) as string;
if (rootDir != null)
{
var file = new FileInfo(Path.Combine(rootDir, imageFileName));
if (file.Exists)
{
if (file.LastWriteTime < DateTime.Now.AddDays(-cacheDays))
return true;
}
}
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
return false;
}
public Image LoadImageFromCache(string imageFileName,
Bitmap defaultBitmap)
{
try
{
using (var stream = new IsolatedStorageFileStream(imageFileName, FileMode.Open, GetIsolatedStorageFile()))
{
return Image.FromStream(stream);
}
}
catch (ArgumentException)
{
// The file is not a valid image, delete it
GetIsolatedStorageFile().DeleteFile(imageFileName);
return defaultBitmap;
}
catch
{
// Other erros, ignore
return defaultBitmap;
}
}
public void CacheImage(string imageFileName, Stream imageStream)
{
using (var output = new IsolatedStorageFileStream(imageFileName, FileMode.Create, GetIsolatedStorageFile()))
{
var buffer = new byte[1024];
int read;
if (imageStream != null)
while ((read = imageStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
}
}
}