Repository navigation
Expand file tree
/
Copy pathMethodsClasses.cs
More file actions
1554 lines (1364 loc) · 65.3 KB
/
Copy pathMethodsClasses.cs
File metadata and controls
1554 lines (1364 loc) · 65.3 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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Forms;
namespace RightClickTools
{
partial class Program
{
// Property enumeration structures and methods for property selector
#pragma warning disable CS0649 // Field is never assigned to, and will always have its default value
public struct PROPERTYKEY
{
public Guid fmtid;
public int pid;
}
#pragma warning restore CS0649
public enum PROPDESC_ENUMFILTER
{
PDEF_ALL = 0,
PDEF_SYSTEM = 1,
PDEF_NONSYSTEM = 2,
PDEF_VIEWABLE = 3,
PDEF_QUERYABLE = 4,
PDEF_INFULLTEXTQUERY = 5,
PDEF_COLUMN = 6,
}
[Flags]
public enum PROPDESC_TYPE_FLAGS
{
PDTF_DEFAULT = 0,
PDTF_MULTIPLEVALUES = 0x1,
PDTF_ISINNATE = 0x2,
PDTF_ISGROUP = 0x4,
PDTF_CANGROUPBY = 0x8,
PDTF_CANSTACKBY = 0x10,
PDTF_ISTREEPROPERTY = 0x20,
PDTF_INCLUDEINFULLTEXTQUERY = 0x40,
PDTF_ISVIEWABLE = 0x80,
PDTF_ISQUERYABLE = 0x100,
PDTF_CANBEPURGED = 0x200,
PDTF_SEARCHRAWVALUE = 0x400,
PDTF_DONTCOERCEEMPTYSTRINGS = 0x800,
PDTF_ALWAYSINSUPPLEMENTALSTORE = 0x1000,
PDTF_ISSYSTEMPROPERTY = unchecked((int)0x80000000),
PDTF_MASK_ALL = unchecked((int)0x80001fff),
}
[DllImport("propsys")]
public static extern int PSEnumeratePropertyDescriptions(PROPDESC_ENUMFILTER filterOn, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IPropertyDescriptionList ppv);
[ComImport, Guid("1F9FC1D0-C39B-4B26-817F-011967D3440E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPropertyDescriptionList
{
int GetCount();
[return: MarshalAs(UnmanagedType.Interface)]
IPropertyDescription GetAt(int iElem, [MarshalAs(UnmanagedType.LPStruct)] Guid riid);
}
[ComImport, Guid("6F79D558-3E96-4549-A1D1-7D75D2288814"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPropertyDescription
{
PROPERTYKEY GetPropertyKey();
[PreserveSig] int GetCanonicalName(out IntPtr zPtr);
int GetPropertyType();
[PreserveSig] int GetDisplayName(out IntPtr zPtr);
[PreserveSig] int GetEditInvitation(out IntPtr zPtr);
PROPDESC_TYPE_FLAGS GetTypeFlags(PROPDESC_TYPE_FLAGS mask);
}
public static string SelectFolder(string currentFolder)
{
// Save user's current "Expand to current folder" setting
int userExpandSetting = 0;
const string expandKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
const string expandValueName = "NavPaneExpandToCurrentFolder";
try
{
using (var key = Registry.CurrentUser.OpenSubKey(expandKeyPath))
{
if (key != null)
{
object value = key.GetValue(expandValueName);
if (value != null)
{
userExpandSetting = (int)value;
}
}
}
}
catch { }
// Enable "Expand to current folder"
try
{
using (var key = Registry.CurrentUser.CreateSubKey(expandKeyPath))
{
key.SetValue(expandValueName, 1, RegistryValueKind.DWord);
}
}
catch { }
FolderPicker fd = new FolderPicker
{
Title = "", // This will display "Select Folder" in the current OS language
InputPath = !string.IsNullOrEmpty(currentFolder) && System.IO.Directory.Exists(currentFolder) ? currentFolder : "",
Multiselect = false
};
if (fd.ShowDialog(IntPtr.Zero) == true && !string.IsNullOrEmpty(fd.ResultPath))
{
currentFolder = fd.ResultPath;
}
// Restore user's original "Expand to current folder" setting
try
{
using (var key = Registry.CurrentUser.CreateSubKey(expandKeyPath))
{
key.SetValue(expandValueName, userExpandSetting, RegistryValueKind.DWord);
}
}
catch { }
return currentFolder;
}
// Courtesy of Simon Mourier https://stackoverflow.com/a/66187224/15764378
public class FolderPicker
{
private readonly List<string> _resultPaths = new List<string>();
private readonly List<string> _resultNames = new List<string>();
public IReadOnlyList<string> ResultPaths => _resultPaths;
public IReadOnlyList<string> ResultNames => _resultNames;
public string ResultPath => ResultPaths.FirstOrDefault();
public string ResultName => ResultNames.FirstOrDefault();
public virtual string InputPath { get; set; }
public virtual bool ForceFileSystem { get; set; }
public virtual bool Multiselect { get; set; }
public virtual string Title { get; set; }
public virtual string OkButtonLabel { get; set; }
public virtual string FileNameLabel { get; set; }
protected virtual int SetOptions(int options)
{
if (ForceFileSystem)
{
options |= (int)FOS.FOS_FORCEFILESYSTEM;
}
if (Multiselect)
{
options |= (int)FOS.FOS_ALLOWMULTISELECT;
}
return options;
}
public virtual bool? ShowDialog(IntPtr owner, bool throwOnError = false)
{
var dialog = (IFileOpenDialog)new FileOpenDialog();
if (!string.IsNullOrEmpty(InputPath))
{
if (CheckHr(SHCreateItemFromParsingName(InputPath, null, typeof(IShellItem).GUID, out var item), throwOnError) != 0)
return null;
dialog.SetFolder(item);
}
var options = FOS.FOS_PICKFOLDERS;
options = (FOS)SetOptions((int)options);
dialog.SetOptions(options);
if (Title != null)
{
dialog.SetTitle(Title);
}
if (OkButtonLabel != null)
{
dialog.SetOkButtonLabel(OkButtonLabel);
}
if (FileNameLabel != null)
{
dialog.SetFileNameLabel(FileNameLabel);
}
if (owner == IntPtr.Zero)
{
owner = Process.GetCurrentProcess().MainWindowHandle;
if (owner == IntPtr.Zero)
{
owner = GetDesktopWindow();
}
}
var hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED)
return null;
if (CheckHr(hr, throwOnError) != 0)
return null;
if (CheckHr(dialog.GetResults(out var items), throwOnError) != 0)
return null;
items.GetCount(out var count);
for (var i = 0; i < count; i++)
{
items.GetItemAt(i, out var item);
CheckHr(item.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING, out var path), throwOnError);
CheckHr(item.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out var name), throwOnError);
if (path != null || name != null)
{
_resultPaths.Add(path);
_resultNames.Add(name);
}
}
return true;
}
private static int CheckHr(int hr, bool throwOnError)
{
if (hr != 0 && throwOnError) Marshal.ThrowExceptionForHR(hr);
return hr;
}
[DllImport("shell32")]
private static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IBindCtx pbc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem ppv);
[DllImport("user32")]
private static extern IntPtr GetDesktopWindow();
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] // CLSID_FileOpenDialog
private class FileOpenDialog { }
[ComImport, Guid("d57c7288-d4ad-4768-be02-9d969532d960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IFileOpenDialog
{
[PreserveSig] int Show(IntPtr parent); // IModalWindow
[PreserveSig] int SetFileTypes(); // not fully defined
[PreserveSig] int SetFileTypeIndex(int iFileType);
[PreserveSig] int GetFileTypeIndex(out int piFileType);
[PreserveSig] int Advise(); // not fully defined
[PreserveSig] int Unadvise();
[PreserveSig] int SetOptions(FOS fos);
[PreserveSig] int GetOptions(out FOS pfos);
[PreserveSig] int SetDefaultFolder(IShellItem psi);
[PreserveSig] int SetFolder(IShellItem psi);
[PreserveSig] int GetFolder(out IShellItem ppsi);
[PreserveSig] int GetCurrentSelection(out IShellItem ppsi);
[PreserveSig] int SetFileName([MarshalAs(UnmanagedType.LPWStr)] string pszName);
[PreserveSig] int GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[PreserveSig] int SetTitle([MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[PreserveSig] int SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string pszText);
[PreserveSig] int SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[PreserveSig] int GetResult(out IShellItem ppsi);
[PreserveSig] int AddPlace(IShellItem psi, int alignment);
[PreserveSig] int SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[PreserveSig] int Close(int hr);
[PreserveSig] int SetClientGuid(); // not fully defined
[PreserveSig] int ClearClientData();
[PreserveSig] int SetFilter([MarshalAs(UnmanagedType.IUnknown)] object pFilter);
[PreserveSig] int GetResults(out IShellItemArray ppenum);
[PreserveSig] int GetSelectedItems([MarshalAs(UnmanagedType.IUnknown)] out object ppsai);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItem
{
[PreserveSig] int BindToHandler(); // not fully defined
[PreserveSig] int GetParent(); // not fully defined
[PreserveSig] int GetDisplayName(SIGDN sigdnName, [MarshalAs(UnmanagedType.LPWStr)] out string ppszName);
[PreserveSig] int GetAttributes(); // not fully defined
[PreserveSig] int Compare(); // not fully defined
}
[ComImport, Guid("b63ea76d-1f85-456f-a19c-48159efa858b"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IShellItemArray
{
[PreserveSig] int BindToHandler(); // not fully defined
[PreserveSig] int GetPropertyStore(); // not fully defined
[PreserveSig] int GetPropertyDescriptionList(); // not fully defined
[PreserveSig] int GetAttributes(); // not fully defined
[PreserveSig] int GetCount(out int pdwNumItems);
[PreserveSig] int GetItemAt(int dwIndex, out IShellItem ppsi);
[PreserveSig] int EnumItems(); // not fully defined
}
private enum SIGDN : uint
{
SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000,
SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000,
SIGDN_FILESYSPATH = 0x80058000,
SIGDN_NORMALDISPLAY = 0,
SIGDN_PARENTRELATIVE = 0x80080001,
SIGDN_PARENTRELATIVEEDITING = 0x80031001,
SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001,
SIGDN_PARENTRELATIVEPARSING = 0x80018001,
SIGDN_URL = 0x80068000
}
[Flags]
private enum FOS
{
FOS_OVERWRITEPROMPT = 0x2,
FOS_STRICTFILETYPES = 0x4,
FOS_NOCHANGEDIR = 0x8,
FOS_PICKFOLDERS = 0x20,
FOS_FORCEFILESYSTEM = 0x40,
FOS_ALLNONSTORAGEITEMS = 0x80,
FOS_NOVALIDATE = 0x100,
FOS_ALLOWMULTISELECT = 0x200,
FOS_PATHMUSTEXIST = 0x800,
FOS_FILEMUSTEXIST = 0x1000,
FOS_CREATEPROMPT = 0x2000,
FOS_SHAREAWARE = 0x4000,
FOS_NOREADONLYRETURN = 0x8000,
FOS_NOTESTFILECREATE = 0x10000,
FOS_HIDEMRUPLACES = 0x20000,
FOS_HIDEPINNEDPLACES = 0x40000,
FOS_NODEREFERENCELINKS = 0x100000,
FOS_OKBUTTONNEEDSINTERACTION = 0x200000,
FOS_DONTADDTORECENT = 0x2000000,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_DEFAULTNOMINIMODE = 0x20000000,
FOS_FORCEPREVIEWPANEON = 0x40000000,
FOS_SUPPORTSTREAMABLEITEMS = unchecked((int)0x80000000)
}
}
//Credit for the following TrustedInstaller code: https://github.com/rara64/GetTrustedInstaller
class TrustedInstaller
{
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetHandleInformation(IntPtr hObject, HANDLE_FLAGS dwMask, HANDLE_FLAGS dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, ref IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
public static void Run(int parentProcessId, string binaryPath)
{
const int PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000;
const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
const uint CREATE_NEW_CONSOLE = 0x00000010;
var pInfo = new PROCESS_INFORMATION();
var siEx = new STARTUPINFOEX();
IntPtr lpValueProc = IntPtr.Zero;
IntPtr hSourceProcessHandle = IntPtr.Zero;
var lpSize = IntPtr.Zero;
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
siEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
InitializeProcThreadAttributeList(siEx.lpAttributeList, 1, 0, ref lpSize);
IntPtr parentHandle = OpenProcess(ProcessAccessFlags.CreateProcess | ProcessAccessFlags.DuplicateHandle, false, parentProcessId);
lpValueProc = Marshal.AllocHGlobal(IntPtr.Size);
Marshal.WriteIntPtr(lpValueProc, parentHandle);
UpdateProcThreadAttribute(siEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, lpValueProc, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero);
var ps = new SECURITY_ATTRIBUTES();
var ts = new SECURITY_ATTRIBUTES();
ps.nLength = Marshal.SizeOf(ps);
ts.nLength = Marshal.SizeOf(ts);
// lpCommandLine was used instead of lpApplicationName to allow for arguments to be passed
bool ret = CreateProcess(null, binaryPath, ref ps, ref ts, true, EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE, IntPtr.Zero, null, ref siEx, out pInfo);
String stringPid = pInfo.dwProcessId.ToString();
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
[MarshalAs(UnmanagedType.Bool)]
public bool bInheritHandle;
}
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
[Flags]
enum HANDLE_FLAGS : uint
{
None = 0,
INHERIT = 1,
PROTECT_FROM_CLOSE = 2
}
}
// Drive and folder information detection methods
public static string GetFileSystem(string driveLetter)
{
try
{
System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(driveLetter);
return driveInfo.DriveFormat;
}
catch
{
return "Unknown";
}
}
public static string GetDriveTypeLabel(string driveLetter)
{
try
{
System.IO.DriveInfo driveInfo = new System.IO.DriveInfo(driveLetter);
switch (driveInfo.DriveType)
{
case System.IO.DriveType.Fixed:
return "Local Disk";
case System.IO.DriveType.Removable:
return "USB Drive";
case System.IO.DriveType.Network:
return "Network Drive";
case System.IO.DriveType.CDRom:
return "CD-ROM Drive";
case System.IO.DriveType.Ram:
return "RAM Disk";
default:
return "Unknown";
}
}
catch
{
return "Unknown";
}
}
public static bool IsAFTDEnabled()
{
try
{
string key = @"HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell";
string v = (Registry.GetValue(key, "FolderType", "") as string);
if (string.IsNullOrEmpty(v))
{
return true; // AFTD is enabled (default)
}
v = v.ToLower();
// List of folder types that, when hard set, disable Automatic Folder Type Discovery
string[] folderTypes = {
"notspecified", "accountpictures", "contacts", "contacts.library", "contacts.searchresults",
"documents", "documents.library", "documents.searchresults", "downloads", "fileitemapis",
"generic", "generic.library", "generic.searchresults", "homefolder", "music",
"music.library", "music.searchresults", "opensearch", "otherusers", "otherusers.searchresults",
"pictures", "pictures.library", "pictures.searchresults", "publisheditems", "publisheditems.searchresults",
"searchconnector", "searches", "storageproviderdocuments", "storageprovidergeneric", "storageprovidermusic",
"storageproviderpictures", "storageprovidervideos", "userfiles", "userfiles.searchresults",
"userslibraries", "userslibraries.searchresults", "videos", "videos.library", "videos.searchresults"
};
return Array.IndexOf(folderTypes, v) == -1; // If NOT in the list, AFTD is enabled (no override set)
}
catch
{
return true; // Assume enabled if we can't read the registry
}
}
public static void SetAFTDEnabled(bool enable)
{
try
{
string keyPath = @"Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell";
using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
{
if (enable)
{
// Remove the FolderType value to enable AFTD
try
{
key.DeleteValue("FolderType", false);
}
catch { }
}
else
{
// Set to a valid folder type to disable AFTD
key.SetValue("FolderType", "Generic", RegistryValueKind.String);
}
}
}
catch { }
}
public static bool IsAlwaysShowIconsEnabled()
{
try
{
string key = @"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
object value = Registry.GetValue(key, "IconsOnly", 0);
if (value != null && value is int)
{
return (int)value == 1;
}
return false; // Default is thumbnails enabled
}
catch
{
return false;
}
}
public static void SetAlwaysShowIcons(bool enable)
{
try
{
string keyPath = @"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced";
using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
{
key.SetValue("IconsOnly", enable ? 1 : 0, RegistryValueKind.DWord);
}
}
catch { }
}
public static bool IsFolderThumbnailsDisabled()
{
try
{
string key = @"HKEY_CURRENT_USER\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell";
string value = Registry.GetValue(key, "Logo", "") as string;
if (string.IsNullOrEmpty(value))
{
return false; // Default is enabled (thumbnails shown)
}
return value.ToLower() == "none"; // "none" means disabled
}
catch
{
return false;
}
}
public static void SetFolderThumbnailsDisabled(bool disable)
{
try
{
string keyPath = @"Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell";
using (var key = Registry.CurrentUser.CreateSubKey(keyPath))
{
if (disable)
{
key.SetValue("Logo", "none", RegistryValueKind.String);
}
else
{
// Remove the value to enable thumbnails
try
{
key.DeleteValue("Logo", false);
}
catch { }
}
}
}
catch { }
}
// INI file helper class for desktop.ini manipulation
public class IniFileHelper
{
private string filePath;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);
public IniFileHelper(string path)
{
filePath = path;
}
public void WriteValue(string section, string key, string value)
{
WritePrivateProfileString(section, key, value, filePath);
}
public string ReadValue(string section, string key)
{
const int size = 255;
System.Text.StringBuilder builder = new System.Text.StringBuilder(size);
GetPrivateProfileString(section, key, "", builder, size, filePath);
return builder.ToString();
}
public void UpdateValue(string section, string key, string value)
{
WriteValue(section, key, value);
}
}
// Folder type application methods
public static void ApplyFolderType(string folderType, string directory)
{
string desktopIniPath = System.IO.Path.Combine(directory, "desktop.ini");
if (folderType == "None")
{
if (System.IO.File.Exists(desktopIniPath))
{
// Remove the FolderType entry
IniFileHelper iniFile = new IniFileHelper(desktopIniPath);
iniFile.WriteValue("ViewState", "FolderType", null);
// Check if there are other meaningful entries
if (!HasOtherEntries(desktopIniPath))
{
System.IO.File.Delete(desktopIniPath);
}
}
return;
}
if (System.IO.File.Exists(desktopIniPath))
{
UpdateIniValue(desktopIniPath, "ViewState", "FolderType", folderType);
}
else
{
CreateIniFile(desktopIniPath);
UpdateIniValue(desktopIniPath, "ViewState", "FolderType", folderType);
System.IO.File.SetAttributes(desktopIniPath, System.IO.File.GetAttributes(desktopIniPath) | System.IO.FileAttributes.System | System.IO.FileAttributes.Hidden);
}
}
public static bool HasOtherEntries(string filePath)
{
try
{
string[] lines = System.IO.File.ReadAllLines(filePath);
int entryCount = 0;
foreach (string line in lines)
{
string trimmedLine = line.Trim();
// Count lines that contain "=" and are not empty or commented
if (!trimmedLine.StartsWith(";") && trimmedLine.Contains("=") && !string.IsNullOrWhiteSpace(trimmedLine))
{
entryCount++;
}
}
// If there are other entries remaining, keep the file
return entryCount > 0;
}
catch
{
return true; // If we can't read the file, assume it has other entries to be safe
}
}
private static void CreateIniFile(string filePath)
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
{
writer.WriteLine("[ViewState]");
writer.WriteLine("FolderType=Generic");
}
}
private static void UpdateIniValue(string filePath, string section, string key, string value)
{
IniFileHelper iniFile = new IniFileHelper(filePath);
iniFile.UpdateValue(section, key, value);
}
// Get the current folder type from desktop.ini
public static string GetCurrentFolderType(string directory)
{
try
{
string desktopIniPath = System.IO.Path.Combine(directory, "desktop.ini");
if (System.IO.File.Exists(desktopIniPath))
{
IniFileHelper iniFile = new IniFileHelper(desktopIniPath);
string folderType = iniFile.ReadValue("ViewState", "FolderType");
if (!string.IsNullOrEmpty(folderType))
{
// Normalize the folder type to match our display names
folderType = folderType.Trim();
// Map internal folder types to display names
switch (folderType.ToLower())
{
case "generic":
return "General Items";
case "documents":
return "Documents";
case "pictures":
return "Pictures";
case "music":
return "Music";
case "videos":
return "Videos";
default:
return folderType; // Return as-is if not recognized
}
}
}
}
catch { }
return "(Not Set)"; // Default if no folder type is set
}
// Get the newest image file in a directory
public static string GetNewestImageFileInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.ToList();
if (imageFiles.Count == 0)
return null;
string newestFile = null;
DateTime newestDate = DateTime.MinValue;
foreach (var file in imageFiles)
{
var fileInfo = new System.IO.FileInfo(file);
var latestDate = fileInfo.CreationTime > fileInfo.LastWriteTime
? fileInfo.CreationTime
: fileInfo.LastWriteTime;
if (latestDate > newestDate)
{
newestDate = latestDate;
newestFile = file;
}
}
return newestFile;
}
catch
{
return null;
}
}
// Get the two newest image files in a directory
public static List<string> GetTwoNewestImageFilesInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
var result = new List<string>();
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.Select(f => new System.IO.FileInfo(f))
.Select(fi => new
{
Path = fi.FullName,
Date = fi.CreationTime > fi.LastWriteTime ? fi.CreationTime : fi.LastWriteTime
})
.OrderByDescending(x => x.Date)
.Take(2)
.ToList();
foreach (var imageFile in imageFiles)
{
result.Add(imageFile.Path);
}
}
catch { }
return result;
}
// Get the four newest image files in a directory
public static List<string> GetFourNewestImageFilesInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
var result = new List<string>();
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.Select(f => new System.IO.FileInfo(f))
.Select(fi => new
{
Path = fi.FullName,
Date = fi.CreationTime > fi.LastWriteTime ? fi.CreationTime : fi.LastWriteTime
})
.OrderByDescending(x => x.Date)
.Take(4)
.ToList();
foreach (var imageFile in imageFiles)
{
result.Add(imageFile.Path);
}
}
catch { }
return result;
}
// Get the first image file alphabetically in a directory
public static string GetFirstImageFileInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
.ToList();
return imageFiles.Count > 0 ? imageFiles[0] : null;
}
catch
{
return null;
}
}
// Get the first two image files alphabetically in a directory
public static List<string> GetFirstTwoImageFilesInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
var result = new List<string>();
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
.Take(2)
.ToList();
result.AddRange(imageFiles);
}
catch { }
return result;
}
// Get the first four image files alphabetically in a directory
public static List<string> GetFirstFourImageFilesInDirectory(string dirPath)
{
var supportedExtensions = new[]
{
".bmp", ".dib", ".rle",
".jpg", ".jpeg", ".jpe", ".jfif",
".tif", ".tiff",
".png"
};
var result = new List<string>();
try
{
var imageFiles = System.IO.Directory.GetFiles(dirPath)
.Where(f => supportedExtensions.Any(ext =>
f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)
.Take(4)
.ToList();
result.AddRange(imageFiles);
}
catch { }