-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
347 lines (328 loc) · 15.7 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace SharePointFileShareMigrationAnalysis
{
class Program
{
internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
internal static int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
internal const int MAX_PATH = 260;
[StructLayout(LayoutKind.Sequential)]
internal struct FILETIME
{
internal uint dwLowDateTime;
internal uint dwHighDateTime;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct WIN32_FIND_DATA
{
internal FileAttributes dwFileAttributes;
internal FILETIME ftCreationTime;
internal FILETIME ftLastAccessTime;
internal FILETIME ftLastWriteTime;
internal int nFileSizeHigh;
internal int nFileSizeLow;
internal int dwReserved0;
internal int dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
internal string cFileName;
// not using this
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
internal string cAlternate;
}
[Flags]
internal enum EFileAccess : uint
{
GenericRead = 0x80000000,
GenericWrite = 0x40000000,
GenericExecute = 0x20000000,
GenericAll = 0x10000000,
}
[Flags]
internal enum EFileShare : uint
{
None = 0x00000000,
Read = 0x00000001,
Write = 0x00000002,
Delete = 0x00000004,
}
internal enum ECreationDisposition : uint
{
New = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5,
}
[Flags]
internal enum EFileAttributes : uint
{
Readonly = 0x00000001,
Hidden = 0x00000002,
System = 0x00000004,
Directory = 0x00000010,
Archive = 0x00000020,
Device = 0x00000040,
Normal = 0x00000080,
Temporary = 0x00000100,
SparseFile = 0x00000200,
ReparsePoint = 0x00000400,
Compressed = 0x00000800,
Offline = 0x00001000,
NotContentIndexed = 0x00002000,
Encrypted = 0x00004000,
Write_Through = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x08000000,
DeleteOnClose = 0x04000000,
BackupSemantics = 0x02000000,
PosixSemantics = 0x01000000,
OpenReparsePoint = 0x00200000,
OpenNoRecall = 0x00100000,
FirstPipeInstance = 0x00080000
}
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern IntPtr FindFirstFile(string lpFileName, out
WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
internal static extern bool FindNextFile(IntPtr hFindFile, out
WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FindClose(IntPtr hFindFile);
internal class DirInfo
{
public long Size { get; set; }
public long Files { get; set; }
}
internal static long byteToGb = 1024 * 1024 * 1024;
internal static string[] hiddenDirs = new string[] {
"_files",
"_Dateien",
"_fichiers",
"_bestanden",
"_file",
"_archivos",
"_tiedostot",
"_pliki",
"_soubory",
"_elemei",
"_ficheiros",
"_arquivos",
"_dosyalar",
"_datoteke",
"_fitxers",
"_failid",
"_fails",
"_bylos",
"_fajlovi",
"_fitxategiak",
"_private" };
public static void Main(string[] args)
{
try
{
using (StreamWriter ffi = new FileInfo("SPShareAnalysis_Files.csv").CreateText())
{
ffi.AutoFlush = true;
lock(ffi){ ffi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { "Path", "Size [Bytes]", "PathLength" }); }
using (StreamWriter cfi = new FileInfo("SPShareAnalysis_Dirs.csv").CreateText())
{
cfi.AutoFlush = true;
lock(cfi){ cfi.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\"", new object[] { "Path", "#Files", "#Dirs", "Size [Bytes]", "TotalSize [Bytes]", "#FilesTotal", "MaxPathLength" }); }
using (StreamWriter efi = new FileInfo("SPShareAnalysis_Errors.csv").CreateText())
{
efi.AutoFlush = true;
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { "Path", "Type", "Error" }); }
using (StreamWriter tfi = new FileInfo("SPShareAnalysis_Types.csv").CreateText())
{
tfi.AutoFlush = true;
lock(tfi){ tfi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { "Type", "Count", "Total Size [Bytes]" }); }
string[] shares = new string[Properties.Settings.Default.Shares.Count];
string[] paths = new string[Properties.Settings.Default.Paths.Count];
Properties.Settings.Default.Shares.CopyTo(shares, 0);
Properties.Settings.Default.Paths.CopyTo(paths, 0);
Dictionary<string, DirInfo> typeInfo = new Dictionary<string, DirInfo>();
Parallel.ForEach(shares, new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount > 1 ? Environment.ProcessorCount - 1 : 1 },
(currentShare) =>
{
string currentPath = paths[Array.IndexOf(shares, currentShare)];
currentPath = currentPath.TrimEnd("/\\".ToCharArray()) + "/";
GetInfo(currentShare, currentShare, currentPath, ffi, cfi, efi, typeInfo);
});
foreach (KeyValuePair<string, DirInfo> type in typeInfo)
lock(tfi){ tfi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { type.Key, type.Value.Files, type.Value.Size }); }
}
}
}
}
}
catch (Exception ex)
{
lock(Console.Error){ Console.Error.WriteLine("An exception happended: " + ex.GetType().ToString()); }
lock(Console.Error){ Console.Error.WriteLine(ex.Message); }
lock(Console.Error){ Console.Error.WriteLine(ex.StackTrace); }
}
}
internal static string GetName(string di)
{
while (di.EndsWith("\\")) { di.TrimEnd("\\".ToCharArray()); }
if (di.IndexOf("\\") == -1) return di;
return di.Substring(di.LastIndexOf("\\") + 1);
}
internal static long GetFileSize(string filePath)
{
WIN32_FIND_DATA findData;
IntPtr findHandle = FindFirstFile(filePath, out findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
return (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
}
else
{
return 0;
}
}
internal static List<string> GetDirectories(string dirName)
{
List<string> results = new List<string>();
WIN32_FIND_DATA findData;
IntPtr findHandle = FindFirstFile(dirName + @"\*", out findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
bool found;
do
{
string currentFileName = findData.cFileName;
if (((int)findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
currentFileName != "." && currentFileName != "..")
{
results.Add(Path.Combine(dirName, currentFileName));
}
found = FindNextFile(findHandle, out findData);
}
while (found);
}
FindClose(findHandle);
return results;
}
internal static List<string> GetFiles(string dirName)
{
List<string> results = new List<string>();
WIN32_FIND_DATA findData;
IntPtr findHandle = FindFirstFile(dirName + @"\*", out findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
bool found;
do
{
string currentFileName = findData.cFileName;
if (((int)findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
results.Add(Path.Combine(dirName, currentFileName));
}
found = FindNextFile(findHandle, out findData);
}
while (found);
}
FindClose(findHandle);
return results;
}
internal static DirInfo GetInfo(string root, string di, string path, StreamWriter ffi, StreamWriter cfi, StreamWriter efi, Dictionary<string, DirInfo> typeInfo)
{
string name = GetName(di);
int dirTotLength = di.Length - root.Length + path.Length;
if (name.IndexOfAny("\\/:*?\"<>|#%".ToCharArray()) > -1)
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "Not allowed character found: \\ / : * ? \" < > | # %" }); }
if (name.ToCharArray()[0] == '~')
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "A name starting with ~ is not allowed" }); }
if (name.ToCharArray()[0] == '.')
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "A name starting with . is not allowed" }); }
foreach (string ending in hiddenDirs)
{
if (name.EndsWith(ending))
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "A name ending in " + ending + " will not be visible" }); }
}
if (name == "forms")
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "A name forms is not allowed" }); }
if (name.Contains("_vti_"))
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "Folder name should not contain _vti_" }); }
if (dirTotLength > 400)
efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "Full folder path can have up to 400 characters" });
List<string> files = GetFiles(di);
List<string> subDirs = GetDirectories(di);
long allFilesSize = 0;
long subDirsSize = 0;
long subDirsFilesCount = files.Count;
if ((files.Count + subDirs.Count) > 5000)
lock (efi) { efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { di, "Dir", "Directory has more than 5000 elements" }); }
long subDirsDirsCount = subDirs.Count;
int maxPathLength = dirTotLength;
Parallel.ForEach(files, new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount > 1 ? Environment.ProcessorCount - 1 : 1 },
(fi) =>
{
long fileSize = GetFileSize(fi);
if (fileSize == 0)
lock (efi) { efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "Zero length" }); }
allFilesSize += fileSize;
string fname = GetName(fi);
int fileTotLength = dirTotLength + 1 + fname.Length;
string fext = "";
if (fname.IndexOf(".") > -1) fext = fname.Substring(fname.LastIndexOf("."));
lock (typeInfo)
{
if (!typeInfo.ContainsKey(fext)) typeInfo.Add(fext, new DirInfo());
typeInfo[fext].Files += 1;
typeInfo[fext].Size += fileSize;
}
if (fname.IndexOfAny("\\/:*?\"<>|#%".ToCharArray()) > -1)
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "Not allowed character found: \\ / : * ? \" < > | # %" }); }
if (fname.ToCharArray()[0] == '~')
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "A name starting with ~ is not allowed" }); }
if (fname.ToCharArray()[0] == '.' && fname.ToCharArray()[1] == '.')
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "A name starting with .. is not allowed" }); }
if (fext == ".tmp" || fext == ".ds_store")
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "File extensions .tmp and .ds_store are not allowed" }); }
if (fname == "desktop.ini" || fname == "thumbs.db" || fname == "ehthumbs.db")
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "File names desktop.ini, thumbs.db and ehthumbs.db are not allowed" }); }
if ((fi.Length / byteToGb) > 2)
lock(efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "Too big. only 2GB allowed" }); }
if (fileTotLength > 400)
lock (efi){ efi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, "File", "Folder name and file name combinations can have up to 400 characters" }); }
if (fileTotLength > maxPathLength)
maxPathLength = fileTotLength;
lock(ffi){ ffi.WriteLine("\"{0}\",\"{1}\",\"{2}\"", new object[] { fi, fileSize, fileTotLength }); }
});
Parallel.ForEach(subDirs, new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount > 1 ? Environment.ProcessorCount - 1 : 1 },
(sdi) =>
{
DirInfo subinfo = GetInfo(root, sdi, path, ffi, cfi, efi, typeInfo);
lock (subDirs)
{
subDirsSize += subinfo.Size;
subDirsFilesCount += subinfo.Files;
}
});
lock(cfi){ cfi.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\"", new object[] { di, files.Count, subDirs.Count, allFilesSize, (allFilesSize + subDirsSize), subDirsFilesCount, maxPathLength }); }
DirInfo info = new DirInfo();
info.Size = allFilesSize + subDirsSize;
info.Files = subDirsFilesCount;
return info;
}
}
}