forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DirectoryImageCache.cs
124 lines (108 loc) · 3.23 KB
/
DirectoryImageCache.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Drawing;
using System.IO;
namespace Gravatar
{
internal class DirectoryImageCache : IImageCache
{
private static Object padlock = new Object();
string cachePath;
public string Path { get { return cachePath; } }
public DirectoryImageCache(string cachePath)
{
this.cachePath = cachePath;
}
public void ClearCache()
{
lock (padlock)
{
if (!Directory.Exists(cachePath))
return;
foreach (string file in Directory.GetFiles(cachePath))
{
try
{
File.Delete(file);
}
catch
{ }
}
}
}
public void DeleteCachedFile(string imageFileName)
{
lock (padlock)
{
if (File.Exists(cachePath + imageFileName))
{
try
{
File.Delete(cachePath + imageFileName);
}
catch
{ }
}
}
}
public bool FileIsCached(string imageFileName)
{
lock (padlock)
{
return File.Exists(cachePath + imageFileName);
}
}
public bool FileIsExpired(string imageFileName, int cacheDays)
{
var file = new FileInfo(cachePath + imageFileName);
if (file.Exists)
{
if (file.LastWriteTime < DateTime.Now.AddDays(-cacheDays))
return true;
}
return false;
}
public Image LoadImageFromCache(string imageFileName, Bitmap defaultBitmap)
{
lock (padlock)
{
try
{
if (!File.Exists(cachePath + imageFileName))
return null;
using (Stream fileStream = new FileStream(cachePath + imageFileName, FileMode.Open, FileAccess.Read))
{
return Image.FromStream(fileStream);
}
}
catch
{
return null;
}
}
}
public void CacheImage(string imageFileName, Stream imageStream)
{
if (!Directory.Exists(cachePath))
Directory.CreateDirectory(cachePath);
lock (padlock)
{
try
{
using (var output = new FileStream(cachePath + imageFileName, FileMode.Create))
{
byte[] buffer = new byte[1024];
int read;
if (imageStream != null)
while ((read = imageStream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
}
catch
{
}
}
}
}
}