teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

追記

2019/03/15 03:33

投稿

Zuishin
Zuishin

スコア28675

answer CHANGED
@@ -3,4 +3,81 @@
3
3
  [Enumerable.Except Method](https://docs.microsoft.com/ja-jp/dotnet/api/system.linq.enumerable.except?view=netframework-4.7.2) を使えば、一方のリストに含まれているが他方には無い項目が取得できます。
4
4
  これをファイル名を対象に二回使えば追加されたファイルと削除されたファイルがわかります。
5
5
 
6
- 変更は [Dictionary<TKey,TValue> Class](https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2) を使うと良いでしょう。まずは片方のリストを、ファイル名をキーに辞書に入れ、次のリストに含まれる項目の一つ一つに対してその辞書に同じファイル名の項目が入っているかどうかを調べます。入っていた場合にはその二つの項目を比較し、更新日時が違えば変更されたことがわかります。
6
+ 変更は [Dictionary<TKey,TValue> Class](https://docs.microsoft.com/ja-jp/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2) を使うと良いでしょう。まずは片方のリストを、ファイル名をキーに辞書に入れ、次のリストに含まれる項目の一つ一つに対してその辞書に同じファイル名の項目が入っているかどうかを調べます。入っていた場合にはその二つの項目を比較し、更新日時が違えば変更されたことがわかります。
7
+
8
+ # 追記
9
+
10
+ こんな感じになります。
11
+
12
+ ```C#
13
+ using System;
14
+ using System.Collections.Generic;
15
+ using System.IO;
16
+ using System.Linq;
17
+
18
+ namespace Etude
19
+ {
20
+ class Program
21
+ {
22
+ static void Main(string[] args)
23
+ {
24
+ string fileMask = "*.txt";
25
+ foreach (var file in Directory.GetFiles(".", fileMask))
26
+ {
27
+ File.Delete(file);
28
+ }
29
+
30
+ File.Create("a.txt").Close();
31
+ File.Create("b.txt").Close();
32
+ File.Create("c.txt").Close();
33
+ var dir = new DirectoryInfo(".");
34
+ var before = dir
35
+ .GetFiles(fileMask)
36
+ .ToDictionary(a => a.FullName);
37
+ Dump(nameof(before), before.Keys);
38
+
39
+ File.Create("d.txt").Close();
40
+ File.Delete("b.txt");
41
+ File.Delete("c.txt");
42
+ File.Create("c.txt").Close();
43
+ var after = dir
44
+ .GetFiles(fileMask)
45
+ .ToDictionary(a => a.FullName);
46
+ Dump(nameof(after), after.Keys);
47
+
48
+ var added = after
49
+ .Keys
50
+ .Except(before.Keys)
51
+ .Select(a => after[a])
52
+ .ToArray();
53
+ Dump(nameof(added), added.Select(a => a.FullName));
54
+
55
+ var removed = before
56
+ .Keys
57
+ .Except(after.Keys)
58
+ .Select(a => before[a])
59
+ .ToArray();
60
+ Dump(nameof(removed), removed.Select(a => a.FullName));
61
+
62
+ var changed = before
63
+ .Keys
64
+ .Where(a => after.ContainsKey(a))
65
+ .Where(a => after[a].LastWriteTime != before[a].LastWriteTime)
66
+ .ToArray();
67
+ Dump(nameof(changed), changed);
68
+
69
+ Console.ReadKey();
70
+ }
71
+
72
+ static void Dump(string title, IEnumerable<string> files)
73
+ {
74
+ Console.WriteLine($"[{title}]");
75
+ foreach (var file in files)
76
+ {
77
+ Console.WriteLine(file);
78
+ }
79
+ Console.WriteLine();
80
+ }
81
+ }
82
+ }
83
+ ```