-
Notifications
You must be signed in to change notification settings - Fork 3
/
Util.cs
295 lines (249 loc) · 9.99 KB
/
Util.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Microsoft.Win32;
namespace cacheCopy
{
static class Util
{
//Generate new random every time used. Must sit outside of the function, as static, otherwise there would be no randomness.
private static Random random = new Random((int)DateTime.Now.Ticks);
/// <summary>
/// Get list of all the files in the directory.
/// This scans all the files inside of the subdirs
/// </summary>
/// <param name="directory">string with directory path</param>
/// <returns>List with FileInfo</returns>
public static List<FileInfo> WalkDirectory(string directory)
{
return WalkDirectory(new DirectoryInfo(directory));
}
/// <summary>
/// Get list of all the files in the directory.
/// This scans all the files inside of the subdirs
/// </summary>
/// <param name="directory">DirectoryInfo to scan</param>
/// <returns>List with FileInfo</returns>
public static List<FileInfo> WalkDirectory(DirectoryInfo directory)
{
if (!Directory.Exists(directory.FullName))
{
return new List<FileInfo>();
}
List<FileInfo> files = new List<FileInfo>();
// Scan all files in the current path
foreach (FileInfo file in directory.GetFiles())
{
files.Add(file);
}
DirectoryInfo[] subDirectories = directory.GetDirectories();
// Scan the directories in the current directory and call this method
// again to go one level into the directory tree
foreach (DirectoryInfo subDirectory in subDirectories)
{
files.AddRange(WalkDirectory(subDirectory));
}
return files;
}
public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
{
if (@this.InvokeRequired)
{
@this.Invoke(action, new object[] { @this });
}
else
{
action(@this);
}
}
/// <summary>
/// Reads the key from win registry
/// </summary>
/// <param name="keyName">Name of the key.</param>
/// <param name="valueName">Name of the value.</param>
/// <returns></returns>
public static string ReadRegistryKey(string keyName, string valueName)
{
string value;
try
{
value = (String)Registry.GetValue(keyName, valueName, "");
}
catch (Exception)
{
return "";
}
return value;
}
/// <summary>
/// Finds the registry key in a registry folder
/// </summary>
/// <param name="folder">The folder to search in</param>
/// <param name="startsWith">The search criteria - key must start with this value</param>
/// <returns> Full key name if found, empty string if nothing found</returns>
public static string FindRegistryKey(RegistryKey regFolder, String startsWith)
{
if (null == regFolder)
return "";
var subKeys = regFolder.GetSubKeyNames();
String key = subKeys.FirstOrDefault(k => k.StartsWith(startsWith));
if (!string.IsNullOrEmpty(key))
{
return regFolder.Name + @"\" + key;
}
else
{
return "";
}
}
/// <summary>
/// Determines whether a value is present at the specified key name
/// </summary>
/// <param name="keyName">Name of the key.</param>
/// <param name="valueName">Name of the value.</param>
/// <returns>
/// <c>true</c> if value is present at the specified key name; otherwise, <c>false</c>.
/// </returns>
public static bool IsRegistryValuePresent(string keyName, string valueName)
{
string value = "";
try
{
value = (String)Registry.GetValue(keyName, valueName, "");
}
catch (Exception)
{
// if exception thrown, there is no value there
return false;
}
if (value != "")
{
return true;
}
return false;
}
/// <summary>
/// Writes exception information to log file.
/// </summary>
public static void WriteToLogFile(Exception e)
{
String directory = Application.LocalUserAppDataPath;
String fileFullPath = Path.Combine(directory, "cacheCopy_errors.txt");
StreamWriter sw = new StreamWriter(fileFullPath, true);
sw.WriteLine("################################################");
sw.WriteLine();
sw.WriteLine("Error occurred at #{0}", DateTime.Now.ToString());
sw.WriteLine(e.ToString());
sw.WriteLine();
sw.Dispose();
}
public delegate String StringProfileFinder(String s);
/// <summary>
/// With list of possible paths, we need to find first one that is not empty
///
/// Go through array of possible values, apply passed in function and check if the
/// result of the function is not empty - return it.
///
/// If no result returned by any possible values, return empty string
/// </summary>
/// <param name="possiblePaths">The possible paths.</param>
/// <param name="function">The function to apply to the possible path</param>
/// <returns>first non-empty result or empty string if no value found</returns>
public static string GetExistingPathByString(String[] possiblePaths, StringProfileFinder function)
{
foreach (string path in possiblePaths)
{
if (function(path) != null)
return path;
}
return String.Empty;
}
public delegate Boolean BooleanProfileFinder(String s);
/// <summary>
/// With list of possible paths, we need to find first one that is not empty
///
/// Go through array of possible values, apply passed in function and check if the
/// result of the function is not empty - return it.
///
/// If no result returned by any possible values, return empty string
/// </summary>
/// <param name="possiblePaths">The possible paths.</param>
/// <param name="function">The function to apply to the possible path</param>
/// <returns>first non-empty result or empty string if no value found</returns>
public static string GetExistingPathByBoolean(String[] possiblePaths, BooleanProfileFinder function)
{
foreach (string path in possiblePaths)
{
if (function(path))
return path;
}
return String.Empty;
}
/// <summary>
/// Generates the random string of given length.
/// String consists of uppercase letters only.
/// </summary>
/// <param name="size">The required length of the string.</param>
/// <returns>String</returns>
public static string GenerateRandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(CreateRandomIntForString());
builder.Append(ch);
}
return builder.ToString();
}
/// <summary>
/// Create a random number corresponding to ASCII uppercase or a digit
/// </summary>
/// <returns>Integer between 48-57 or between 65-90</returns>
private static int CreateRandomIntForString()
{
//ASCII codes
//48-57 = digits
//65-90 = Uppercase letters
//97-122 = lowercase letters
int i;
do
{
i = Convert.ToInt32(random.Next(48, 90));
} while (i > 57 && i < 65);
return i;
}
/// <summary>
/// Pads the given number to a maximum number it can go.
/// i.e. for given number 45 and maximum count as 7784, result would be 0045
/// </summary>
/// <param name="number">The number.</param>
/// <param name="maxNumber">The max number.</param>
/// <returns></returns>
public static string PadNumberToMaximum(int number, int maxNumber)
{
int maxLen = maxNumber.ToString().Length;
return number.ToString().PadLeft(maxLen, '0');
}
/// <summary>
/// Determines whether the filename is valid.
///
/// Thanks to Scott Dorman for the solution:
/// http://stackoverflow.com/a/63235/809357
/// </summary>
/// <param name="expression">The filename.</param>
/// <returns>
/// <c>true</c> if the provided filename is valid; otherwise, <c>false</c>.
/// </returns>
public static bool IsValidFileName(this string expression)
{
string sPattern = @"^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)(\..+)?$)[^\x00-\x1f\\?*:\"";|/]+$";
return (Regex.IsMatch(expression, sPattern, RegexOptions.CultureInvariant));
}
}
}