-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileDeleter.cs
387 lines (344 loc) · 12.9 KB
/
FileDeleter.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/**
* Handles cleaning up of temp files.
* Reads path data from a SQLite database and age limit on files.
* All files that match are deleted.
*
* Author: Nicholas Dunnaway
* Version: $Id: FileDeleter.cs,v 1.3.1 2011/07/27 20:11:29 nkd Exp $
*/
using System;
using System.IO;
using System.Data;
namespace Digitalroot.FileDeleter
{
/// <summary>
/// Handles cleaning up of temp files.
/// </summary>
class FileDeleter
{
private static bool _verbose; // Are we in verbose mode?
private const string DBFile = "db.sqlite";
private static readonly SQLiteWrapper.SQLiteWrapper DB = new SQLiteWrapper.SQLiteWrapper(DBFile);
private static bool PathDBInstalled
{
get
{
string tmp = DB.Get("PathDBInstalled");
return tmp == "TRUE";
}
set { DB.Set("PathDBInstalled", value ? "TRUE" : "FALSE"); }
}
/// <summary>
/// App entry point.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Console.WriteLine("");
//Console.Read(); // Pause
// Print the version number.
if (args.Length > 0 && (args[0] == "-v" || args[0] == "-version" || args[0] == "-ver"))
{
string sVersion = "$Revision: 1.3.1 $";
sVersion = sVersion.Replace("$", ""); // Remove the CVS dollar sign.
sVersion = sVersion.Replace("Revision", "Version"); // Replace revision with version.
Console.WriteLine(sVersion);
Exit();
}
try
{
// Check if the database is installed.
if (PathDBInstalled != true)
{
InstallDB(); // Install it
}
// Check if called with out a Parameter.
if (args.Length == 0)
{
var aTmp = new string[1];
aTmp[0] = "run";
ProcessCommands(aTmp);
}
else
{
ProcessCommands(args);
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e);
}
}
/// <summary>
/// Installs the path database.
/// </summary>
private static void InstallDB()
{
DB.RawCmd("CREATE TABLE paths (id INTEGER PRIMARY KEY AUTOINCREMENT, path VARCHAR(250) UNIQUE, age int(4))");
DB.Set("PathDBInstalled", "TRUE");
}
/// <summary>
/// Logic case statement for processing commands.
/// </summary>
private static void ProcessCommands(string[] aParameters)
{
switch (aParameters[0])
{
case "-vb":
// Check if we are doing verbose reporting
if (aParameters.Length == 2 && aParameters[1] == "-v")
{
_verbose = true;
}
break;
case "-add":
// Check if enough parameters were passed.
if (aParameters.Length < 3)
{
ErrorExit("Unable to add path to database. Missing Parameter. See help for more info.");
}
Add(aParameters[1], aParameters[2]);
break;
case "-a":
// Check if enough parameters were passed.
if (aParameters.Length < 3)
{
ErrorExit("Unable to add path to database. Missing Parameter. See help for more info.");
}
Add(aParameters[1], aParameters[2]);
break;
case "-del":
// Check if enough parameters were passed.
if (aParameters.Length < 2)
{
ErrorExit("Unable to delete path from database. Missing Parameter. See help for more info.");
}
Del(aParameters[1]);
break;
case "-d":
// Check if enough parameters were passed.
if (aParameters.Length < 2)
{
ErrorExit("Unable to delete path from database. Missing Parameter. See help for more info.");
}
Del(aParameters[1]);
break;
case "-list":
List();
break;
case "-l":
List();
break;
case "-path":
// Check if enough parameters were passed.
if (aParameters.Length < 3)
{
ErrorExit("Unable to add path to database. Missing Parameter. See help for more info.");
}
int i = int.Parse(aParameters[2]);
DeleteFiles(aParameters[1], i);
break;
case "-p":
// Check if enough parameters were passed.
if (aParameters.Length < 3)
{
ErrorExit("Unable to add path to database. Missing Parameter. See help for more info.");
}
int i2 = int.Parse(aParameters[2]);
DeleteFiles(aParameters[1], i2);
break;
case "-h":
Help();
break;
case "-help":
Help();
break;
case "run":
NormalRun();
break;
default:
Console.WriteLine("Parameter Unknown: Try \"FileDeleter -h\" for help.");
break;
}
}
/// <summary>
/// This runs when called w/o parameters. This will read
/// from the database and loop each directory.
/// </summary>
private static void NormalRun()
{
DataTable results = DB.Select("SELECT path, age FROM paths");
DataRow[] rows = results.Select();
foreach (DataRow r in rows)
{
DeleteFiles(r["path"].ToString(), int.Parse(r["age"].ToString()));
}
}
/// <summary>
/// Deletes a path from the database
/// </summary>
/// <param name="p">PathID of the path to delete.</param>
private static void Del(string p)
{
DB.RawCmd("DELETE FROM paths WHERE id = " + p);
Console.WriteLine("Path deleted.");
}
/// <summary>
/// Prints the error message to the user and exits the app.
/// </summary>
/// <param name="p">Error message to print.</param>
private static void ErrorExit(string p)
{
Console.WriteLine(p);
Exit();
}
/// <summary>
/// Adds a path to check to the database.
/// </summary>
/// <param name="p">Path to check for files.</param>
/// <param name="p2">Delete files over this many days old.</param>
private static void Add(string p, string p2)
{
DB.RawCmd("INSERT INTO paths (path, age) VALUES ('" + p + "', '" + p2 + "')");
Console.WriteLine("Path added to database.");
}
/// <summary>
/// Prints the help items to the screen.
/// </summary>
private static void Help()
{
Console.WriteLine("Usage: FileDeleter [options ...] [parameters]\n");
Console.WriteLine("Options:");
Console.WriteLine("\t-a or -add - Add a new path");
Console.WriteLine("\t\tFileDeleter -a path age\n");
Console.WriteLine("\t-d or -del - Delete a path");
Console.WriteLine("\t\tFileDeleter -d pathid \n");
Console.WriteLine("\t-l or -list - List all paths from database.\n");
Console.WriteLine("\t-p or -path - Delete files from the path older then age. Do not add to database.");
Console.WriteLine("\t\tFileDeleter -p path age\n");
Console.WriteLine("\t-h or -help - This help list.");
}
/// <summary>
/// Prints a list of paths, ages and ids to the screen.
/// </summary>
private static void List()
{
DataTable results = DB.Select("SELECT * FROM paths");
DataRow[] rows = results.Select();
Console.WriteLine("PathID\t Path\t Age");
foreach (DataRow r in rows)
{
foreach (DataColumn c in r.Table.Columns)
{
Console.Write("{0}\t ", r[c]);
}
Console.WriteLine();
}
}
/// <summary>
/// Exits the App
/// </summary>
private static void Exit()
{
//Console.WriteLine("Press any key to continue.");
//Console.Read(); // Pause
Environment.Exit(0);
}
/// <summary>
/// Checks files and del anything over iAge days old
/// </summary>
/// <param name="path">Path you want to clean</param>
/// <param name="age"></param>
private static void DeleteFiles(string path, int age)
{
// Check if DIR is valid.
if (!Directory.Exists(path))
{
Console.WriteLine("The path (" + path + ") is not a valid path.");
Exit();
}
try
{
var di = new DirectoryInfo(path);
FileInfo[] fi = di.GetFiles();
if (_verbose)
{
Console.WriteLine("Number of files: {0}", fi.Length);
Console.WriteLine("The following files exist in the current directory:");
}
// Print out the names of the files in the current directory.
foreach (FileInfo fiTemp in fi)
{
if (_verbose)
{
Console.Write(fiTemp.Name + " ... Checking File ... ");
Console.Write(fiTemp.LastWriteTime.ToShortDateString() + " ... "); // mod date
}
if (fiTemp.LastWriteTime < DateTime.Now.AddDays((age * -1)))
{
// Check if file is over iAge days old. If so del it.
try
{
fiTemp.Delete();
}
catch (Exception e)
{
if (_verbose)
{
Console.WriteLine(e.Message);
}
}
if (_verbose)
{
Console.WriteLine("Deleted.");
}
}
else
{
// If file is less then age days old then we ignore it.
if (_verbose)
{
Console.WriteLine("Ignored.");
}
}
}
// Recursive
DirectoryInfo[] dii = di.GetDirectories();
foreach (DirectoryInfo diTemp in dii)
{
DeleteFiles(diTemp.FullName, age); // Recursive
FileInfo[] fii = diTemp.GetFiles();
if (fii.Length > 0)
{
// There are files in the dir so we can not delete it.
if (_verbose)
{
foreach (FileInfo fiiTemp in fii)
{
Console.WriteLine(fiiTemp.FullName); // Debugging.
}
}
}
else
{
try
{
Directory.Delete(diTemp.FullName);
}
catch (Exception e)
{
if (_verbose)
{
Console.WriteLine(e.Message);
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
}