-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
638 lines (582 loc) · 17.1 KB
/
Program.cs
File metadata and controls
638 lines (582 loc) · 17.1 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
using System;
using System.IO;
using System.Linq;
namespace TouchMax;
/*
* Usage:
* TouchMax +/-HH:MM <file specification>
*
* Pass a file path (with optional wildcards) and the offset to use to
* change the file's last-modified time.
*/
class Program
{
private bool _bTest = false;
private string _strDirectory = ".";
private string _strPattern = string.Empty;
private bool _bSetFiles = false;
private bool _bSetFolders = false;
private bool _bRecurse = false;
private bool _bSetCreation = false;
private bool _bSetModified = false;
// use these for setting relative components
private int _relYears = 0;
private int _relMonths = 0;
// could combine these three into a TimeSpan, but why break the parallels
private int _relDays = 0;
private int _relHours = 0;
private int _relMinutes = 0;
// use these for setting absolute components
private int? _absYear = null;
private int? _absMonth = null;
private int? _absDate = null;
private int? _absHour = null;
private int? _absMinute = null;
// use this for setting "now"
private bool _bUseCreation = false;
private bool _bUseModified = false;
private bool _bUseNow = false;
private readonly DateTime _dtNow = DateTime.Now;
private delegate bool DirectoryInfoHandler(DirectoryInfo dirinfo, string outputPrefix);
private delegate bool FileInfoHandler(FileInfo dirinfo, string outputPrefix);
static void Main(string[] args)
{
if (args.Length < 4)
{
//Console.WriteLine("Command line: " + String.Join(";", args));
ShowUsage();
return;
}
Program pgm = new();
try
{
pgm.ParseArguments(args);
}
catch (Exception)
{
return;
}
pgm.Touch(pgm._strDirectory, pgm._strPattern);
}
private Program() { }
private void Touch(string strPath, string strPattern)
{
ProcessSubdirectoriesAndFiles(nLevel: 0, OffsetDirectory, OffsetFile, strPath, strPattern);
}
/// <summary>
/// This function processes every subdirectory and file in the passed
/// directory that matches the passed pattern.
/// For each file, it calls the passed file handler delegate (if it's not null).
/// For each directory, it calls the passed directory handler delegate (if it's not null).
/// If a delegate returns false, it stops processing the files/dirs.
/// If it returns true, it continues.
/// </summary>
/// <param name="nLevel">Level of recursion</param>
/// <param name="handlerDirInfo">Delegate to process a folder.</param>
/// <param name="handlerFileInfo">Delegate to process a file.</param>
/// <param name="strPath"></param>
/// <param name="strPattern"></param>
/// <returns>True when the recursion is finished. False to continue.</returns>
private bool ProcessSubdirectoriesAndFiles(int nLevel,
DirectoryInfoHandler handlerDirInfo,
FileInfoHandler handlerFileInfo,
string strPath,
string strPattern)
{
// can throw System.ArgumentException
DirectoryInfo dir = new(strPath);
if (!dir.Exists)
{
Console.WriteLine($"The directory {strPath} does not exist.");
return true;
}
Console.WriteLine();
string strIndent = string.Empty.PadLeft(nLevel, '\t');
Console.WriteLine(strIndent + dir.FullName + Path.AltDirectorySeparatorChar);
/*
* Since we're using a pattern, the subdirectories might not (probably
* won't) match it. So, we process any files that match the pattern.
* Then, separately, we process all subdirectories.
*
* Alternative: FileSystemInfo fsinfos = dir.GetFileSystemInfos(strPattern);
*/
/*
* Process each file
* If any return false, we quit.
*/
if (_bSetFiles && (handlerFileInfo is not null))
{
try
{
if (dir.GetFiles(strPattern).Any(fileinfo => !handlerFileInfo(fileinfo, strIndent)))
{
return false;
}
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
}
/*
* Process each folder
* If any return false, we quit.
*/
if (_bSetFolders && (handlerDirInfo is not null))
{
try
{
if (dir.GetDirectories(strPattern).Any(dirinfo => !handlerDirInfo(dirinfo, strIndent)))
{
return false;
}
}
catch (DirectoryNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
}
/*
* Recurse into all subfolders
*/
if (_bRecurse)
{
foreach (DirectoryInfo dirinfo in dir.GetDirectories())
{
ProcessSubdirectoriesAndFiles(nLevel + 1, handlerDirInfo!, handlerFileInfo!, dirinfo.FullName, strPattern);
}
}
return true;
}
private bool OffsetFile(FileInfo fileinfo, string outputPrefix)
{
Console.WriteLine($"{outputPrefix}{fileinfo.Name}");
DateTime dtCreation = File.GetCreationTime(fileinfo.FullName);
DateTime dtModified = File.GetLastWriteTime(fileinfo.FullName);
if (_bSetCreation)
{
DateTime dtNew = DetermineNewDateTime(dtCreation, dtCreation, dtModified);
if (_bTest)
{
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtCreation.ToString(), dtNew.ToString());
}
else
{
try
{
File.SetCreationTime(fileinfo.FullName, dtNew);
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtCreation.ToString(), File.GetCreationTime(fileinfo.FullName).ToString());
}
catch (IOException ex)
{
Console.WriteLine($"Unable to set Creation-Time of {fileinfo.Name} to {dtNew}.");
Console.WriteLine(ex.Message);
}
}
}
if (_bSetModified)
{
DateTime dtNew = DetermineNewDateTime(dtModified, dtCreation, dtModified);
if (_bTest)
{
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtModified.ToString(), dtNew.ToString());
}
else
{
try
{
File.SetLastWriteTime(fileinfo.FullName, dtNew);
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtModified.ToString(), File.GetLastWriteTime(fileinfo.FullName).ToString());
}
catch (IOException ex)
{
Console.WriteLine($"Unable to set Modified-Time of {fileinfo.Name} to {dtNew}.");
Console.WriteLine(ex.Message);
}
}
}
return true;
}
private bool OffsetDirectory(DirectoryInfo dirinfo, string outputPrefix)
{
Console.WriteLine($"{outputPrefix}{dirinfo.Name}/");
DateTime dtCreation = Directory.GetCreationTime(dirinfo.FullName);
DateTime dtModified = Directory.GetLastWriteTime(dirinfo.FullName);
if (_bSetCreation)
{
DateTime dtNew = DetermineNewDateTime(dtCreation, dtCreation, dtModified);
if (_bTest)
{
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtCreation.ToString(), dtNew.ToString());
}
else
{
try
{
Directory.SetCreationTime(dirinfo.FullName, dtNew);
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtCreation.ToString(), Directory.GetCreationTime(dirinfo.FullName).ToString());
}
catch (IOException ex)
{
Console.WriteLine($"Unable to set Creation-Time of {dirinfo.Name} to {dtNew}.");
Console.WriteLine(ex.Message);
}
}
}
if (_bSetModified)
{
DateTime dtNew = DetermineNewDateTime(dtModified, dtCreation, dtModified);
if (_bTest)
{
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtModified.ToString(), dtNew.ToString());
}
else
{
try
{
Directory.SetLastWriteTime(dirinfo.FullName, dtNew);
Console.WriteLine("{0}{1} => {2}", outputPrefix, dtModified.ToString(), Directory.GetLastWriteTime(dirinfo.FullName).ToString());
}
catch (IOException ex)
{
Console.WriteLine($"Unable to set Modified-Time of {dirinfo.Name} to {dtNew}.");
Console.WriteLine(ex.Message);
}
}
}
return true;
}
private DateTime DetermineNewDateTime(DateTime dt, DateTime dtCreation, DateTime dtModified)
{
/*
* First, determine if we should start with the file's date/time
* or if we should start with the current time.
*/
DateTime dtNew = dt;
if (_bUseNow)
{
dtNew = _dtNow;
}
else if (_bUseCreation)
{
dtNew = dtCreation;
}
else if (_bUseModified)
{
dtNew = dtModified;
}
/*
* Next, apply any absolute settings that were specified
*/
try
{
if (_absYear.HasValue)
{
dtNew = new DateTime(_absYear.Value, dtNew.Month, dtNew.Day, dtNew.Hour, dtNew.Minute, dtNew.Second);
}
if (_absMonth.HasValue)
{
dtNew = new DateTime(dtNew.Year, _absMonth.Value, dtNew.Day, dtNew.Hour, dtNew.Minute, dtNew.Second);
}
if (_absDate.HasValue)
{
dtNew = new DateTime(dtNew.Year, dtNew.Month, _absDate.Value, dtNew.Hour, dtNew.Minute, dtNew.Second);
}
if (_absHour.HasValue)
{
dtNew = new DateTime(dtNew.Year, dtNew.Month, dtNew.Day, _absHour.Value, dtNew.Minute, dtNew.Second);
}
if (_absMinute.HasValue)
{
dtNew = new DateTime(dtNew.Year, dtNew.Month, dtNew.Day, dtNew.Hour, _absMinute.Value, dtNew.Second);
}
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
throw;
}
/*
* Finally, apply any specified relative changes.
*/
dtNew = dtNew.AddYears(_relYears);
dtNew = dtNew.AddMonths(_relMonths);
dtNew = dtNew.AddDays(_relDays);
dtNew = dtNew.AddHours(_relHours);
dtNew = dtNew.AddMinutes(_relMinutes);
return dtNew;
}
private void ParseArguments(string[] args)
{
foreach (string a in args)
{
try
{
if (a.StartsWith("-") || a.StartsWith("/"))
{
string key = a[1..].ToLower();
if (key.StartsWith("test"))
{
_bTest = true;
continue;
}
else if (key.StartsWith("recurse"))
{
_bRecurse = true;
continue;
}
else if (key.StartsWith("setfiles"))
{
_bSetFiles = true;
continue;
}
else if (key.StartsWith("setfolders"))
{
_bSetFolders = true;
continue;
}
else if (key.StartsWith("setcreation"))
{
_bSetCreation = true;
continue;
}
else if (key.StartsWith("setmodified"))
{
_bSetModified = true;
continue;
}
else if (key.StartsWith("usenow"))
{
_bUseNow = true;
continue;
}
else if (key.StartsWith("usecreation"))
{
_bUseCreation = true;
continue;
}
else if (key.StartsWith("usemodified"))
{
_bUseModified = true;
continue;
}
switch (a[1])
{
case 'Y':
{
int n = ParseArgumentNumber(a);
if (a[2] == '=')
{
_absYear = n;
}
else
{
_relYears = n;
}
break;
}
case 'M':
{
int n = ParseArgumentNumber(a);
if (a[2] == '=')
{
_absMonth = n;
}
else
{
_relMonths = n;
}
break;
}
case 'D':
{
int n = ParseArgumentNumber(a);
if (a[2] == '=')
{
_absDate = n;
}
else
{
_relDays = n;
}
break;
}
case 'h':
{
int n = ParseArgumentNumber(a);
if (a[2] == '=')
{
_absHour = n;
}
else
{
_relHours = n;
}
break;
}
case 'm':
{
int n = ParseArgumentNumber(a);
if (a[2] == '=')
{
_absMinute = n;
}
else
{
_relMinutes = n;
}
break;
}
default:
Console.WriteLine($"Unrecognized switch: {a}");
throw new ArgumentException("Unrecognized switch", a);
}
continue;
}
// maybe it's the pattern
if (string.IsNullOrEmpty(_strPattern))
{
_strPattern = a;
/*
* The user may have specified a path (absolute or relative) and
* we need to split them up.
*/
_strDirectory = Path.GetDirectoryName(_strPattern) ?? ".";
_strPattern = Path.GetFileName(_strPattern);
if (string.IsNullOrEmpty(_strDirectory))
{
_strDirectory = ".";
}
}
else
{
Console.WriteLine($"Too many arguments: {a}");
}
}
catch (ArgumentOutOfRangeException /*ex*/)
{
Console.WriteLine($"Invalid argument value: {a}");
throw;
}
}
if (_bTest)
{
Console.WriteLine();
Console.WriteLine("** TEST MODE **");
Console.WriteLine("Recurse? " + (_bRecurse ? "YES" : "NO"));
Console.WriteLine("Set files? " + (_bSetFiles ? "YES" : "NO"));
Console.WriteLine("Set folders? " + (_bSetFolders ? "YES" : "NO"));
Console.WriteLine("Now: " + _dtNow.ToString());
Console.WriteLine("Base: Use " + (_bUseNow ? "NOW" : _bUseCreation ? "CREATION" : "MODIFIED"));
if ((_absYear is not null) || (_absMonth is not null) || (_absDate is not null) || (_absHour is not null) || (_absMinute is not null))
{
Console.WriteLine("Absolute:");
if (_absYear.HasValue)
Console.WriteLine("\tyear = " + _absYear);
if (_absMonth.HasValue)
Console.WriteLine("\tmonth = " + _absMonth);
if (_absDate.HasValue)
Console.WriteLine("\tdate = " + _absDate);
if (_absHour.HasValue)
Console.WriteLine("\thour = " + _absHour);
if (_absMinute.HasValue)
Console.WriteLine("\tminute = " + _absMinute);
}
if ((_relYears != 0) || (_relMonths != 0) || (_relDays != 0) || (_relHours != 0) || (_relMinutes != 0))
{
Console.WriteLine("Relative:");
if (_relYears != 0)
Console.WriteLine("\tyears = " + _relYears);
if (_relMonths != 0)
Console.WriteLine("\tmonths = " + _relMonths);
if (_relDays != 0)
Console.WriteLine("\tdays = " + _relDays);
if (_relHours != 0)
Console.WriteLine("\thour = " + _relHours);
if (_relMinutes != 0)
Console.WriteLine("\tminute = " + _relMinutes);
}
Console.WriteLine("Directory: " + _strDirectory);
Console.WriteLine("Pattern: " + _strPattern);
}
if (!_bSetFiles && !_bSetFolders)
{
Console.WriteLine("You must set file or folder timestamps.");
Environment.Exit(-1);
}
if (!_bSetCreation && !_bSetModified)
{
Console.WriteLine("You must set creation or modified timestamp.");
Environment.Exit(-1);
}
static int ParseArgumentNumber(string s)
{
try
{
// + or - or =
switch (s[2])
{
case '-': return -short.Parse(s[3..]);
case '+': return short.Parse(s[3..]);
case '=': return short.Parse(s[3..]);
default:
Console.WriteLine($"Must use +, -, or = after switch {s}");
break;
}
}
catch (FormatException ex)
{
Console.WriteLine(ex.Message);
throw;
}
return 0;
}
}
static void ShowUsage()
{
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
var exeName = assembly.GetName().Name;
/// assembly.Location is empty for single-file package, so we use this.
System.Diagnostics.FileVersionInfo versionFile = System.Diagnostics.FileVersionInfo.GetVersionInfo(Path.Combine(AppContext.BaseDirectory, $"{exeName}.exe"));
Console.WriteLine();
Console.WriteLine("{0} {1} {2}", versionFile.CompanyName ?? string.Empty, versionFile.ProductName ?? string.Empty, versionFile.ProductVersion ?? string.Empty);
Console.WriteLine("{0}", versionFile.LegalCopyright ?? string.Empty);
Console.WriteLine("12noon.com");
Console.WriteLine();
Console.WriteLine("USAGE");
Console.WriteLine(" [/test] [/setfiles] [/setfolders] [/recurse] [/setcreation] [/setmodified] [/usenow|/usecreation|/usemodified]");
Console.WriteLine(" [/Y+|-|=#] [/M+|-|=#] [/D+|-|=#] [/h+|-|=#] [/m+|-|=#] <pattern>");
Console.WriteLine("\t/setfiles: set file timestamps");
Console.WriteLine("\t/setfolders: set folder timestamps");
Console.WriteLine("\t/recurse: process subfolders");
Console.WriteLine("\t/setcreation: change creation time");
Console.WriteLine("\t/setmodified: change modified time");
Console.WriteLine("\t/usenow: set timestamp to current time first");
Console.WriteLine("\t/usecreation: set timestamp to file's creation time first");
Console.WriteLine("\t/usemodified: set timestamp to file's modified time first");
Console.WriteLine("\t/Y - year, /M - month, /D - date, /h - hour, /m - minute");
Console.WriteLine("\t\t(January is 1, etc. Dates are 1-31.)");
Console.WriteLine("\t\t+ increments the current value by the specified amount");
Console.WriteLine("\t\t- decrements the current value by the specified amount");
Console.WriteLine("\t\t= sets to the specified value");
Console.WriteLine();
Console.WriteLine("PROCESS");
Console.WriteLine("These are the steps it takes to set a file or folder's timestamp:");
Console.WriteLine("\t1. Set timestamp to now, if specified");
Console.WriteLine("\t2. Apply absolute values, if any");
Console.WriteLine("\t3. Apply relative changes, if any");
Console.WriteLine();
Console.WriteLine("EXAMPLES");
Console.WriteLine("Forgot to set camera ahead one hour for Daylight Saving Time. Set Creation-Time of all JPG files in all folders ahead one hour:");
Console.WriteLine("\ttouchmax.exe /recurse /setfiles /setcreation /h+1 *.jpg");
Console.WriteLine();
Console.WriteLine("Set Modified-Time of text files to a month ago and ten minutes ahead:");
Console.WriteLine("\ttouchmax.exe /setfiles /setmodified /usenow /M-1 /m+10 *.txt");
Console.WriteLine();
Console.WriteLine("Set Creation-Time to three days before the ModifiedTime:");
Console.WriteLine("\ttouchmax.exe /setfiles /setmodified /usemodified /D-3 *.txt");
Console.WriteLine();
Console.WriteLine("Set a file's Modified-Time to 15 Sep 2008:");
Console.WriteLine("\ttouchmax.exe /setfiles /setmodified /usemodified /Y=2008 /M=9 /D=15 test.txt");
}
}