-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
FileSystem.Windows.cs
776 lines (660 loc) · 36.2 KB
/
FileSystem.Windows.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
internal static partial class FileSystem
{
public static void Encrypt(string path)
{
string fullPath = Path.GetFullPath(path);
if (!Interop.Advapi32.EncryptFile(fullPath))
{
ThrowExceptionEncryptDecryptFail(fullPath);
}
}
public static void Decrypt(string path)
{
string fullPath = Path.GetFullPath(path);
if (!Interop.Advapi32.DecryptFile(fullPath))
{
ThrowExceptionEncryptDecryptFail(fullPath);
}
}
private static unsafe void ThrowExceptionEncryptDecryptFail(string fullPath)
{
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED)
{
// Check to see if the file system support the Encrypted File System (EFS)
string name = DriveInfoInternal.NormalizeDriveName(Path.GetPathRoot(fullPath)!);
using (DisableMediaInsertionPrompt.Create())
{
if (!Interop.Kernel32.GetVolumeInformation(name, null, 0, null, null, out int fileSystemFlags, null, 0))
{
errorCode = Marshal.GetLastPInvokeError();
throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
if ((fileSystemFlags & Interop.Kernel32.FILE_SUPPORTS_ENCRYPTION) == 0)
{
throw new NotSupportedException(SR.PlatformNotSupported_FileEncryption);
}
}
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
public static void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite);
if (errorCode != Interop.Errors.ERROR_SUCCESS)
{
string fileName = destFullPath;
if (errorCode != Interop.Errors.ERROR_FILE_EXISTS)
{
// For a number of error codes (sharing violation, path not found, etc) we don't know if the problem was with
// the source or dest file. Try reading the source file.
using (SafeFileHandle handle = Interop.Kernel32.CreateFile(sourceFullPath, Interop.Kernel32.GenericOperations.GENERIC_READ, FileShare.Read, FileMode.Open, 0))
{
if (handle.IsInvalid)
fileName = sourceFullPath;
}
if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED)
{
if (DirectoryExists(destFullPath))
throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED);
}
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName);
}
}
public static void ReplaceFile(string sourceFullPath, string destFullPath, string? destBackupFullPath, bool ignoreMetadataErrors)
{
int flags = ignoreMetadataErrors ? Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS : 0;
if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero))
{
throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastPInvokeError());
}
}
public static void DeleteFile(string fullPath)
{
bool r = Interop.Kernel32.DeleteFile(fullPath);
if (!r)
{
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND)
return;
else
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public static FileAttributes GetAttributes(string fullPath) =>
(FileAttributes)GetAttributeData(fullPath, returnErrorOnNotFound: true).dwFileAttributes;
public static FileAttributes GetAttributes(SafeFileHandle fileHandle) =>
(FileAttributes)GetAttributeData(fileHandle).dwFileAttributes;
public static DateTimeOffset GetCreationTime(string fullPath) =>
GetAttributeData(fullPath).ftCreationTime.ToDateTimeOffset();
public static DateTimeOffset GetCreationTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftCreationTime.ToDateTimeOffset();
public static DateTimeOffset GetLastAccessTime(string fullPath) =>
GetAttributeData(fullPath).ftLastAccessTime.ToDateTimeOffset();
public static DateTimeOffset GetLastAccessTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftLastAccessTime.ToDateTimeOffset();
public static DateTimeOffset GetLastWriteTime(string fullPath) =>
GetAttributeData(fullPath).ftLastWriteTime.ToDateTimeOffset();
public static DateTimeOffset GetLastWriteTime(SafeFileHandle fileHandle) =>
GetAttributeData(fileHandle).ftLastWriteTime.ToDateTimeOffset();
internal static Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA GetAttributeData(string fullPath, bool returnErrorOnNotFound = false)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fullPath, ref data, returnErrorOnNotFound);
return errorCode != Interop.Errors.ERROR_SUCCESS
? throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath)
: data;
}
internal static Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA GetAttributeData(SafeFileHandle fileHandle)
{
Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = default;
int errorCode = FillAttributeInfo(fileHandle, ref data);
return errorCode != Interop.Errors.ERROR_SUCCESS
? throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileHandle.Path)
: data;
}
private static int FillAttributeInfo(SafeFileHandle fileHandle, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data)
{
if (!Interop.Kernel32.GetFileInformationByHandle(
fileHandle,
out Interop.Kernel32.BY_HANDLE_FILE_INFORMATION fileInformationData))
{
return Marshal.GetLastPInvokeError();
}
PopulateAttributeData(ref data, fileInformationData);
return Interop.Errors.ERROR_SUCCESS;
}
private static void PopulateAttributeData(ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, in Interop.Kernel32.BY_HANDLE_FILE_INFORMATION fileInformationData)
{
data.dwFileAttributes = (int)fileInformationData.dwFileAttributes;
data.ftCreationTime = fileInformationData.ftCreationTime;
data.ftLastAccessTime = fileInformationData.ftLastAccessTime;
data.ftLastWriteTime = fileInformationData.ftLastWriteTime;
data.nFileSizeHigh = fileInformationData.nFileSizeHigh;
data.nFileSizeLow = fileInformationData.nFileSizeLow;
}
private static void MoveDirectory(string sourceFullPath, string destFullPath, bool _ /*isCaseSensitiveRename*/)
{
// Source and destination must have the same root.
ReadOnlySpan<char> sourceRoot = Path.GetPathRoot(sourceFullPath);
ReadOnlySpan<char> destinationRoot = Path.GetPathRoot(destFullPath);
if (!sourceRoot.Equals(destinationRoot, StringComparison.OrdinalIgnoreCase))
{
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
}
if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath, overwrite: false))
{
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND)
throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath);
if (errorCode == Interop.Errors.ERROR_ALREADY_EXISTS)
throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_ALREADY_EXISTS, destFullPath);
// This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons.
if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp.
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode));
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
public static void MoveFile(string sourceFullPath, string destFullPath, bool overwrite)
{
if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath, overwrite))
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
private static SafeFileHandle OpenHandleToWriteAttributes(string fullPath, bool asDirectory)
{
if (fullPath.Length == PathInternal.GetRootLength(fullPath) && fullPath[1] == Path.VolumeSeparatorChar)
{
// intentionally not fullpath, most upstack public APIs expose this as path.
throw new ArgumentException(SR.Arg_PathIsVolume, "path");
}
int dwFlagsAndAttributes = Interop.Kernel32.FileOperations.FILE_FLAG_OPEN_REPARSE_POINT;
if (asDirectory)
{
dwFlagsAndAttributes |= Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS;
}
SafeFileHandle handle = Interop.Kernel32.CreateFile(
fullPath,
Interop.Kernel32.FileOperations.FILE_WRITE_ATTRIBUTES,
FileShare.ReadWrite | FileShare.Delete,
FileMode.Open,
dwFlagsAndAttributes);
if (handle.IsInvalid)
{
int errorCode = Marshal.GetLastPInvokeError();
// NT5 oddity - when trying to open "C:\" as a File,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath)))
errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
handle.Dispose();
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
return handle;
}
public static void RemoveDirectory(string fullPath, bool recursive)
{
if (!recursive)
{
RemoveDirectoryInternal(fullPath, topLevel: true);
return;
}
Interop.Kernel32.WIN32_FIND_DATA findData = default;
// FindFirstFile($path) (used by GetFindData) fails with ACCESS_DENIED when user has no ListDirectory rights
// but FindFirstFile($path/*") (used by RemoveDirectoryRecursive) works fine in such scenario.
// So we ignore it here and let RemoveDirectoryRecursive throw if FindFirstFile($path/*") fails with ACCESS_DENIED.
GetFindData(fullPath, isDirectory: true, ignoreAccessDenied: true, ref findData);
if (IsNameSurrogateReparsePoint(ref findData))
{
// Don't recurse
RemoveDirectoryInternal(fullPath, topLevel: true);
return;
}
// We want extended syntax so we can delete "extended" subdirectories and files
// (most notably ones with trailing whitespace or periods)
fullPath = PathInternal.EnsureExtendedPrefix(fullPath);
RemoveDirectoryRecursive(fullPath, ref findData, topLevel: true);
}
private static void GetFindData(string fullPath, bool isDirectory, bool ignoreAccessDenied, ref Interop.Kernel32.WIN32_FIND_DATA findData)
{
using SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Path.TrimEndingDirectorySeparator(fullPath), ref findData);
if (handle.IsInvalid)
{
int errorCode = Marshal.GetLastPInvokeError();
// File not found doesn't make much sense coming from a directory.
if (isDirectory && errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND)
errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND;
if (ignoreAccessDenied && errorCode == Interop.Errors.ERROR_ACCESS_DENIED)
return;
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
private static bool IsNameSurrogateReparsePoint(ref Interop.Kernel32.WIN32_FIND_DATA data)
{
// Name surrogates are reparse points that point to other named entities local to the file system.
// Reparse points can be used for other types of files, notably OneDrive placeholder files. We
// should treat reparse points that are not name surrogates as any other directory, e.g. recurse
// into them. Surrogates should just be detached.
//
// See
// https://github.com/dotnet/runtime/issues/23646
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365511.aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365197.aspx
return ((FileAttributes)data.dwFileAttributes & FileAttributes.ReparsePoint) != 0
&& (data.dwReserved0 & 0x20000000) != 0; // IsReparseTagNameSurrogate
}
private static void RemoveDirectoryRecursive(string fullPath, ref Interop.Kernel32.WIN32_FIND_DATA findData, bool topLevel)
{
int errorCode;
Exception? exception = null;
using (SafeFindHandle handle = Interop.Kernel32.FindFirstFile(Path.Join(fullPath, "*"), ref findData))
{
if (handle.IsInvalid)
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath);
do
{
if ((findData.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0)
{
// File
string fileName = findData.cFileName.GetStringFromFixedBuffer();
if (!Interop.Kernel32.DeleteFile(Path.Combine(fullPath, fileName)) && exception == null)
{
errorCode = Marshal.GetLastPInvokeError();
// We don't care if something else deleted the file first
if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND)
{
exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName);
}
}
}
else
{
// Directory, skip ".", "..".
if (findData.cFileName.FixedBufferEqualsString(".") || findData.cFileName.FixedBufferEqualsString(".."))
continue;
string fileName = findData.cFileName.GetStringFromFixedBuffer();
if (!IsNameSurrogateReparsePoint(ref findData))
{
// Not a reparse point, or the reparse point isn't a name surrogate, recurse.
try
{
RemoveDirectoryRecursive(
Path.Combine(fullPath, fileName),
findData: ref findData,
topLevel: false);
}
catch (Exception e)
{
exception ??= e;
}
}
else
{
// Name surrogate reparse point, don't recurse, simply remove the directory.
// If a mount point, we have to delete the mount point first.
if (findData.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT)
{
// Mount point. Unmount using full path plus a trailing '\'.
// (Note: This doesn't remove the underlying directory)
string mountPoint = Path.Join(fullPath, fileName, PathInternal.DirectorySeparatorCharAsString);
if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint) && exception == null)
{
errorCode = Marshal.GetLastPInvokeError();
if (errorCode != Interop.Errors.ERROR_SUCCESS &&
errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND)
{
exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName);
}
}
}
// Note that RemoveDirectory on a symbolic link will remove the link itself.
if (!Interop.Kernel32.RemoveDirectory(Path.Combine(fullPath, fileName)) && exception == null)
{
errorCode = Marshal.GetLastPInvokeError();
if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND)
{
exception = Win32Marshal.GetExceptionForWin32Error(errorCode, fileName);
}
}
}
}
} while (Interop.Kernel32.FindNextFile(handle, ref findData));
if (exception != null)
throw exception;
errorCode = Marshal.GetLastPInvokeError();
if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_NO_MORE_FILES)
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
// As we successfully removed all of the files we shouldn't care about the directory itself
// not being empty. As file deletion is just a marker to remove the file when all handles
// are closed we could still have undeleted contents.
RemoveDirectoryInternal(fullPath, topLevel: topLevel, allowDirectoryNotEmpty: true);
}
private static void RemoveDirectoryInternal(string fullPath, bool topLevel, bool allowDirectoryNotEmpty = false)
{
if (!Interop.Kernel32.RemoveDirectory(fullPath))
{
int errorCode = Marshal.GetLastPInvokeError();
switch (errorCode)
{
case Interop.Errors.ERROR_FILE_NOT_FOUND:
// File not found doesn't make much sense coming from a directory delete.
errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND;
goto case Interop.Errors.ERROR_PATH_NOT_FOUND;
case Interop.Errors.ERROR_PATH_NOT_FOUND:
// We only throw for the top level directory not found, not for any contents.
if (!topLevel)
return;
break;
case Interop.Errors.ERROR_DIR_NOT_EMPTY:
if (allowDirectoryNotEmpty)
return;
break;
case Interop.Errors.ERROR_ACCESS_DENIED:
// This conversion was originally put in for Win9x. Keeping for compatibility.
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath));
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
}
public static void SetAttributes(string fullPath, FileAttributes attributes)
{
if (Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes))
{
return;
}
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER)
throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes));
throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath);
}
public static unsafe void SetAttributes(SafeFileHandle fileHandle, FileAttributes attributes)
{
var basicInfo = new Interop.Kernel32.FILE_BASIC_INFO
{
FileAttributes = (uint)attributes
};
if (!Interop.Kernel32.SetFileInformationByHandle(
fileHandle,
Interop.Kernel32.FileBasicInfo,
&basicInfo,
(uint)sizeof(Interop.Kernel32.FILE_BASIC_INFO)))
{
throw Win32Marshal.GetExceptionForLastWin32Error(fileHandle.Path);
}
}
// Default values indicate "no change". Use defaults so that we don't force callsites to be aware of the default values
private static void SetFileTime(
string fullPath,
bool asDirectory,
long creationTime = -1,
long lastAccessTime = -1,
long lastWriteTime = -1,
long changeTime = -1,
uint fileAttributes = 0)
{
using SafeFileHandle handle = OpenHandleToWriteAttributes(fullPath, asDirectory);
SetFileTime(handle, fullPath, creationTime, lastAccessTime, lastWriteTime, changeTime, fileAttributes);
}
private static unsafe void SetFileTime(
SafeFileHandle fileHandle,
string? fullPath = null,
long creationTime = -1,
long lastAccessTime = -1,
long lastWriteTime = -1,
long changeTime = -1,
uint fileAttributes = 0)
{
var basicInfo = new Interop.Kernel32.FILE_BASIC_INFO
{
CreationTime = creationTime,
LastAccessTime = lastAccessTime,
LastWriteTime = lastWriteTime,
ChangeTime = changeTime,
FileAttributes = fileAttributes
};
if (!Interop.Kernel32.SetFileInformationByHandle(fileHandle, Interop.Kernel32.FileBasicInfo, &basicInfo, (uint)sizeof(Interop.Kernel32.FILE_BASIC_INFO)))
{
throw Win32Marshal.GetExceptionForLastWin32Error(fullPath ?? fileHandle.Path);
}
}
public static void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, creationTime: time.ToFileTime());
public static void SetCreationTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, creationTime: time.ToFileTime());
public static void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, lastAccessTime: time.ToFileTime());
public static void SetLastAccessTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, lastAccessTime: time.ToFileTime());
public static void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
=> SetFileTime(fullPath, asDirectory, lastWriteTime: time.ToFileTime());
public static void SetLastWriteTime(SafeFileHandle fileHandle, DateTimeOffset time)
=> SetFileTime(fileHandle, lastWriteTime: time.ToFileTime());
public static string[] GetLogicalDrives()
=> DriveInfoInternal.GetLogicalDrives();
internal static void CreateSymbolicLink(string path, string pathToTarget, bool isDirectory)
{
Interop.Kernel32.CreateSymbolicLink(path, pathToTarget, isDirectory);
}
internal static FileSystemInfo? ResolveLinkTarget(string linkPath, bool returnFinalTarget, bool isDirectory)
{
string? targetPath = returnFinalTarget ?
GetFinalLinkTarget(linkPath, isDirectory) :
GetImmediateLinkTarget(linkPath, isDirectory, throwOnError: true, returnFullPath: true);
return targetPath == null ? null :
isDirectory ? new DirectoryInfo(targetPath) : new FileInfo(targetPath);
}
internal static string? GetLinkTarget(string linkPath, bool isDirectory)
=> GetImmediateLinkTarget(linkPath, isDirectory, throwOnError: false, returnFullPath: false);
/// <summary>
/// Gets reparse point information associated to <paramref name="linkPath"/>.
/// </summary>
/// <returns>The immediate link target, absolute or relative or null if the file is not a supported link.</returns>
internal static unsafe string? GetImmediateLinkTarget(string linkPath, bool isDirectory, bool throwOnError, bool returnFullPath)
{
using SafeFileHandle handle = OpenSafeFileHandle(linkPath,
Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS |
Interop.Kernel32.FileOperations.FILE_FLAG_OPEN_REPARSE_POINT);
if (handle.IsInvalid)
{
if (!throwOnError)
{
return null;
}
int error = Marshal.GetLastPInvokeError();
// File not found doesn't make much sense coming from a directory.
if (isDirectory && error == Interop.Errors.ERROR_FILE_NOT_FOUND)
{
error = Interop.Errors.ERROR_PATH_NOT_FOUND;
}
throw Win32Marshal.GetExceptionForWin32Error(error, linkPath);
}
byte[] buffer = ArrayPool<byte>.Shared.Rent(Interop.Kernel32.MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
try
{
bool success;
fixed (byte* pBuffer = buffer)
{
success = Interop.Kernel32.DeviceIoControl(
handle,
dwIoControlCode: Interop.Kernel32.FSCTL_GET_REPARSE_POINT,
lpInBuffer: null,
nInBufferSize: 0,
lpOutBuffer: pBuffer,
nOutBufferSize: Interop.Kernel32.MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
out _,
IntPtr.Zero);
}
if (!success)
{
if (!throwOnError)
{
return null;
}
int error = Marshal.GetLastPInvokeError();
// The file or directory is not a reparse point.
if (error == Interop.Errors.ERROR_NOT_A_REPARSE_POINT)
{
return null;
}
throw Win32Marshal.GetExceptionForWin32Error(error, linkPath);
}
Span<byte> bufferSpan = new(buffer);
success = MemoryMarshal.TryRead(bufferSpan, out Interop.Kernel32.SymbolicLinkReparseBuffer rbSymlink);
Debug.Assert(success);
// We always use SubstituteName(Offset|Length) instead of PrintName(Offset|Length),
// the latter is just the display name of the reparse point and it can show something completely unrelated to the target.
if (rbSymlink.ReparseTag == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_SYMLINK)
{
int offset = sizeof(Interop.Kernel32.SymbolicLinkReparseBuffer) + rbSymlink.SubstituteNameOffset;
int length = rbSymlink.SubstituteNameLength;
Span<char> targetPath = MemoryMarshal.Cast<byte, char>(bufferSpan.Slice(offset, length));
bool isRelative = (rbSymlink.Flags & Interop.Kernel32.SYMLINK_FLAG_RELATIVE) != 0;
if (!isRelative)
{
// Absolute target is in NT format and we need to clean it up before return it to the user.
if (targetPath.StartsWith(PathInternal.UncNTPathPrefix.AsSpan()))
{
// We need to prepend the Win32 equivalent of UNC NT prefix.
return Path.Join(PathInternal.UncPathPrefix.AsSpan(), targetPath.Slice(PathInternal.UncNTPathPrefix.Length));
}
return GetTargetPathWithoutNTPrefix(targetPath);
}
else if (returnFullPath)
{
return Path.Join(Path.GetDirectoryName(linkPath.AsSpan()), targetPath);
}
else
{
return targetPath.ToString();
}
}
else if (rbSymlink.ReparseTag == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT)
{
success = MemoryMarshal.TryRead(bufferSpan, out Interop.Kernel32.MountPointReparseBuffer rbMountPoint);
Debug.Assert(success);
int offset = sizeof(Interop.Kernel32.MountPointReparseBuffer) + rbMountPoint.SubstituteNameOffset;
int length = rbMountPoint.SubstituteNameLength;
Span<char> targetPath = MemoryMarshal.Cast<byte, char>(bufferSpan.Slice(offset, length));
// Unlike symbolic links, mount point paths cannot be relative.
Debug.Assert(!PathInternal.IsPartiallyQualified(targetPath));
// Mount points cannot point to a remote location.
Debug.Assert(!targetPath.StartsWith(PathInternal.UncNTPathPrefix.AsSpan()));
return GetTargetPathWithoutNTPrefix(targetPath);
}
return null;
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
static string GetTargetPathWithoutNTPrefix(ReadOnlySpan<char> targetPath)
{
Debug.Assert(targetPath.StartsWith(PathInternal.NTPathPrefix.AsSpan()));
return targetPath.Slice(PathInternal.NTPathPrefix.Length).ToString();
}
}
private static unsafe string? GetFinalLinkTarget(string linkPath, bool isDirectory)
{
Interop.Kernel32.WIN32_FIND_DATA data = default;
GetFindData(linkPath, isDirectory, ignoreAccessDenied: false, ref data);
// The file or directory is not a reparse point.
if ((data.dwFileAttributes & (uint)FileAttributes.ReparsePoint) == 0 ||
// Only symbolic links and mount points are supported at the moment.
(data.dwReserved0 != Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_SYMLINK &&
data.dwReserved0 != Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT))
{
return null;
}
// We try to open the final file since they asked for the final target.
using SafeFileHandle handle = OpenSafeFileHandle(linkPath,
Interop.Kernel32.FileOperations.OPEN_EXISTING |
Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS);
if (handle.IsInvalid)
{
// If the handle fails because it is unreachable, is because the link was broken.
// We need to fallback to manually traverse the links and return the target of the last resolved link.
int error = Marshal.GetLastPInvokeError();
if (IsPathUnreachableError(error))
{
return GetFinalLinkTargetSlow(linkPath);
}
throw Win32Marshal.GetExceptionForWin32Error(error, linkPath);
}
const int InitialBufferSize = 4096;
char[] buffer = ArrayPool<char>.Shared.Rent(InitialBufferSize);
try
{
uint result = GetFinalPathNameByHandle(handle, buffer);
// If the function fails because lpszFilePath is too small to hold the string plus the terminating null character,
// the return value is the required buffer size, in TCHARs. This value includes the size of the terminating null character.
if (result > buffer.Length)
{
char[] toReturn = buffer;
buffer = ArrayPool<char>.Shared.Rent((int)result);
ArrayPool<char>.Shared.Return(toReturn);
result = GetFinalPathNameByHandle(handle, buffer);
}
// If the function fails for any other reason, the return value is zero.
if (result == 0)
{
throw Win32Marshal.GetExceptionForLastWin32Error(linkPath);
}
Debug.Assert(PathInternal.IsExtended(new string(buffer, 0, (int)result).AsSpan()));
// GetFinalPathNameByHandle always returns with extended DOS prefix even if the link target was created without one.
// While this does not interfere with correct behavior, it might be unexpected.
// Hence we trim it if the passed-in path to the link wasn't extended.
int start = PathInternal.IsExtended(linkPath.AsSpan()) ? 0 : 4;
return new string(buffer, start, (int)result - start);
}
finally
{
ArrayPool<char>.Shared.Return(buffer);
}
uint GetFinalPathNameByHandle(SafeFileHandle handle, char[] buffer)
{
fixed (char* bufPtr = buffer)
{
return Interop.Kernel32.GetFinalPathNameByHandle(handle, bufPtr, (uint)buffer.Length, Interop.Kernel32.FILE_NAME_NORMALIZED);
}
}
string? GetFinalLinkTargetSlow(string linkPath)
{
// Since all these paths will be passed to CreateFile, which takes a string anyway, it is pointless to use span.
// I am not sure if it's possible to change CreateFile's param to ROS<char> and avoid all these allocations.
// We don't throw on error since we already did all the proper validations before.
string? current = GetImmediateLinkTarget(linkPath, isDirectory, throwOnError: false, returnFullPath: true);
string? prev = null;
while (current != null)
{
prev = current;
current = GetImmediateLinkTarget(current, isDirectory, throwOnError: false, returnFullPath: true);
}
return prev;
}
}
private static unsafe SafeFileHandle OpenSafeFileHandle(string path, int flags)
{
SafeFileHandle handle = Interop.Kernel32.CreateFile(
path,
dwDesiredAccess: 0,
FileShare.ReadWrite | FileShare.Delete,
lpSecurityAttributes: null,
FileMode.Open,
dwFlagsAndAttributes: flags,
hTemplateFile: IntPtr.Zero);
return handle;
}
}
}