-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathFile.cs
1645 lines (1440 loc) · 89.7 KB
/
File.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
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
// 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.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public static partial class File
{
private const int ChunkSize = 8192;
private static Encoding? s_UTF8NoBOM;
// UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter.
private static Encoding UTF8NoBOM => s_UTF8NoBOM ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
internal const int DefaultBufferSize = 4096;
public static StreamReader OpenText(string path)
=> new StreamReader(path);
public static StreamWriter CreateText(string path)
=> new StreamWriter(path, append: false);
public static StreamWriter AppendText(string path)
=> new StreamWriter(path, append: true);
/// <summary>
/// Copies an existing file to a new file.
/// An exception is raised if the destination file already exists.
/// </summary>
public static void Copy(string sourceFileName, string destFileName)
=> Copy(sourceFileName, destFileName, overwrite: false);
/// <summary>
/// Copies an existing file to a new file.
/// If <paramref name="overwrite"/> is false, an exception will be
/// raised if the destination exists. Otherwise it will be overwritten.
/// </summary>
public static void Copy(string sourceFileName, string destFileName, bool overwrite)
{
ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
ArgumentException.ThrowIfNullOrEmpty(destFileName);
FileSystem.CopyFile(Path.GetFullPath(sourceFileName), Path.GetFullPath(destFileName), overwrite);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
public static FileStream Create(string path)
=> Create(path, DefaultBufferSize);
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
public static FileStream Create(string path, int bufferSize)
=> new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
public static FileStream Create(string path, int bufferSize, FileOptions options)
=> new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options);
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On Windows, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
public static void Delete(string path)
{
ArgumentNullException.ThrowIfNull(path);
FileSystem.DeleteFile(Path.GetFullPath(path));
}
// Tests whether a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return false.
public static bool Exists([NotNullWhen(true)] string? path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[^1]))
{
return false;
}
return FileSystem.FileExists(path);
}
catch (ArgumentException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
/// <summary>
/// Initializes a new instance of the <see cref="FileStream" /> class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, additional file options and the allocation size.
/// </summary>
/// <remarks><see cref="FileStream(string,FileStreamOptions)"/> for information about exceptions.</remarks>
public static FileStream Open(string path, FileStreamOptions options) => new FileStream(path, options);
public static FileStream Open(string path, FileMode mode)
=> Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
public static FileStream Open(string path, FileMode mode, FileAccess access)
=> Open(path, mode, access, FileShare.None);
public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
=> new FileStream(path, mode, access, share);
/// <summary>
/// Initializes a new instance of the <see cref="SafeFileHandle" /> class with the specified path, creation mode, read/write and sharing permission, the access other SafeFileHandles can have to the same file, additional file options and the allocation size.
/// </summary>
/// <param name="path">A relative or absolute path for the file that the current <see cref="SafeFileHandle" /> instance will encapsulate.</param>
/// <param name="mode">One of the enumeration values that determines how to open or create the file. The default value is <see cref="FileMode.Open" /></param>
/// <param name="access">A bitwise combination of the enumeration values that determines how the file can be accessed. The default value is <see cref="FileAccess.Read" /></param>
/// <param name="share">A bitwise combination of the enumeration values that determines how the file will be shared by processes. The default value is <see cref="FileShare.Read" />.</param>
/// <param name="preallocationSize">The initial allocation size in bytes for the file. A positive value is effective only when a regular file is being created, overwritten, or replaced.
/// Negative values are not allowed. In other cases (including the default 0 value), it's ignored.</param>
/// <param name="options">An object that describes optional <see cref="SafeFileHandle" /> parameters to use.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> is <see langword="null" />.</exception>
/// <exception cref="T:System.ArgumentException"><paramref name="path" /> is an empty string (""), contains only white space, or contains one or more invalid characters.
/// -or-
/// <paramref name="path" /> refers to a non-file device, such as <c>CON:</c>, <c>COM1:</c>, <c>LPT1:</c>, etc. in an NTFS environment.</exception>
/// <exception cref="T:System.NotSupportedException"><paramref name="path" /> refers to a non-file device, such as <c>CON:</c>, <c>COM1:</c>, <c>LPT1:</c>, etc. in a non-NTFS environment.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="preallocationSize" /> is negative.
/// -or-
/// <paramref name="mode" />, <paramref name="access" />, or <paramref name="share" /> contain an invalid value.</exception>
/// <exception cref="T:System.IO.FileNotFoundException">The file cannot be found, such as when <paramref name="mode" /> is <see cref="FileMode.Truncate" /> or <see cref="FileMode.Open" />, and the file specified by <paramref name="path" /> does not exist. The file must already exist in these modes.</exception>
/// <exception cref="T:System.IO.IOException">An I/O error, such as specifying <see cref="FileMode.CreateNew" /> when the file specified by <paramref name="path" /> already exists, occurred.
/// -or-
/// The disk was full (when <paramref name="preallocationSize" /> was provided and <paramref name="path" /> was pointing to a regular file).
/// -or-
/// The file was too large (when <paramref name="preallocationSize" /> was provided and <paramref name="path" /> was pointing to a regular file).</exception>
/// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
/// <exception cref="T:System.IO.DirectoryNotFoundException">The specified path is invalid, such as being on an unmapped drive.</exception>
/// <exception cref="T:System.UnauthorizedAccessException">The <paramref name="access" /> requested is not permitted by the operating system for the specified <paramref name="path" />, such as when <paramref name="access" /> is <see cref="FileAccess.Write" /> or <see cref="FileAccess.ReadWrite" /> and the file or directory is set for read-only access.
/// -or-
/// <see cref="F:System.IO.FileOptions.Encrypted" /> is specified for <paramref name="options" />, but file encryption is not supported on the current platform.</exception>
/// <exception cref="T:System.IO.PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. </exception>
public static SafeFileHandle OpenHandle(string path, FileMode mode = FileMode.Open, FileAccess access = FileAccess.Read,
FileShare share = FileShare.Read, FileOptions options = FileOptions.None, long preallocationSize = 0)
{
Strategies.FileStreamHelpers.ValidateArguments(path, mode, access, share, bufferSize: 0, options, preallocationSize);
return SafeFileHandle.Open(Path.GetFullPath(path), mode, access, share, options, preallocationSize);
}
// File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
// ToUniversalTime treats this as local.
internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Local)
dateTime = dateTime.ToUniversalTime();
return new DateTimeOffset(dateTime.Ticks, default);
}
public static void SetCreationTime(string path, DateTime creationTime)
=> FileSystem.SetCreationTime(Path.GetFullPath(path), creationTime, asDirectory: false);
/// <summary>
/// Sets the date and time the file or directory was created.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the creation date and time information.
/// </param>
/// <param name="creationTime">
/// A <see cref="DateTime"/> containing the value to set for the creation date and time of <paramref name="fileHandle"/>.
/// This value is expressed in local time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="creationTime"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetCreationTime(SafeFileHandle fileHandle, DateTime creationTime)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetCreationTime(fileHandle, creationTime);
}
public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
=> FileSystem.SetCreationTime(Path.GetFullPath(path), GetUtcDateTimeOffset(creationTimeUtc), asDirectory: false);
/// <summary>
/// Sets the date and time, in coordinated universal time (UTC), that the file or directory was created.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the creation date and time information.
/// </param>
/// <param name="creationTimeUtc">
/// A <see cref="DateTime"/> containing the value to set for the creation date and time of <paramref name="fileHandle"/>.
/// This value is expressed in UTC time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="creationTimeUtc"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetCreationTimeUtc(SafeFileHandle fileHandle, DateTime creationTimeUtc)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetCreationTime(fileHandle, GetUtcDateTimeOffset(creationTimeUtc));
}
public static DateTime GetCreationTime(string path)
=> FileSystem.GetCreationTime(Path.GetFullPath(path)).LocalDateTime;
/// <summary>
/// Returns the creation date and time of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain creation date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the creation date and time for the specified file or
/// directory. This value is expressed in local time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetCreationTime(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetCreationTime(fileHandle).LocalDateTime;
}
public static DateTime GetCreationTimeUtc(string path)
=> FileSystem.GetCreationTime(Path.GetFullPath(path)).UtcDateTime;
/// <summary>
/// Returns the creation date and time, in coordinated universal time (UTC), of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain creation date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the creation date and time for the specified file or
/// directory. This value is expressed in UTC time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetCreationTimeUtc(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetCreationTime(fileHandle).UtcDateTime;
}
public static void SetLastAccessTime(string path, DateTime lastAccessTime)
=> FileSystem.SetLastAccessTime(Path.GetFullPath(path), lastAccessTime, false);
/// <summary>
/// Sets the date and time the specified file or directory was last accessed.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the last access date and time information.
/// </param>
/// <param name="lastAccessTime">
/// A <see cref="DateTime"/> containing the value to set for the last access date and time of <paramref name="fileHandle"/>.
/// This value is expressed in local time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="lastAccessTime"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetLastAccessTime(SafeFileHandle fileHandle, DateTime lastAccessTime)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetLastAccessTime(fileHandle, lastAccessTime);
}
public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
=> FileSystem.SetLastAccessTime(Path.GetFullPath(path), GetUtcDateTimeOffset(lastAccessTimeUtc), false);
/// <summary>
/// Sets the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the last access date and time information.
/// </param>
/// <param name="lastAccessTimeUtc">
/// A <see cref="DateTime"/> containing the value to set for the last access date and time of <paramref name="fileHandle"/>.
/// This value is expressed in UTC time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="lastAccessTimeUtc"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetLastAccessTimeUtc(SafeFileHandle fileHandle, DateTime lastAccessTimeUtc)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetLastAccessTime(fileHandle, GetUtcDateTimeOffset(lastAccessTimeUtc));
}
public static DateTime GetLastAccessTime(string path)
=> FileSystem.GetLastAccessTime(Path.GetFullPath(path)).LocalDateTime;
/// <summary>
/// Returns the last access date and time of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain last access date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the last access date and time for the specified file or
/// directory. This value is expressed in local time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetLastAccessTime(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetLastAccessTime(fileHandle).LocalDateTime;
}
public static DateTime GetLastAccessTimeUtc(string path)
=> FileSystem.GetLastAccessTime(Path.GetFullPath(path)).UtcDateTime;
/// <summary>
/// Returns the last access date and time, in coordinated universal time (UTC), of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain last access date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the last access date and time for the specified file or
/// directory. This value is expressed in UTC time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetLastAccessTimeUtc(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetLastAccessTime(fileHandle).UtcDateTime;
}
public static void SetLastWriteTime(string path, DateTime lastWriteTime)
=> FileSystem.SetLastWriteTime(Path.GetFullPath(path), lastWriteTime, false);
/// <summary>
/// Sets the date and time that the specified file or directory was last written to.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the last write date and time information.
/// </param>
/// <param name="lastWriteTime">
/// A <see cref="DateTime"/> containing the value to set for the last write date and time of <paramref name="fileHandle"/>.
/// This value is expressed in local time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="lastWriteTime"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetLastWriteTime(SafeFileHandle fileHandle, DateTime lastWriteTime)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetLastWriteTime(fileHandle, lastWriteTime);
}
public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
=> FileSystem.SetLastWriteTime(Path.GetFullPath(path), GetUtcDateTimeOffset(lastWriteTimeUtc), false);
/// <summary>
/// Sets the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to set the last write date and time information.
/// </param>
/// <param name="lastWriteTimeUtc">
/// A <see cref="DateTime"/> containing the value to set for the last write date and time of <paramref name="fileHandle"/>.
/// This value is expressed in UTC time.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="lastWriteTimeUtc"/> specifies a value outside the range of dates, times, or both permitted for this operation.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <exception cref="IOException">
/// An I/O error occurred while performing the operation.
/// </exception>
public static void SetLastWriteTimeUtc(SafeFileHandle fileHandle, DateTime lastWriteTimeUtc)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetLastWriteTime(fileHandle, GetUtcDateTimeOffset(lastWriteTimeUtc));
}
public static DateTime GetLastWriteTime(string path)
=> FileSystem.GetLastWriteTime(Path.GetFullPath(path)).LocalDateTime;
/// <summary>
/// Returns the last write date and time of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain last write date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the last write date and time for the specified file or
/// directory. This value is expressed in local time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetLastWriteTime(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetLastWriteTime(fileHandle).LocalDateTime;
}
public static DateTime GetLastWriteTimeUtc(string path)
=> FileSystem.GetLastWriteTime(Path.GetFullPath(path)).UtcDateTime;
/// <summary>
/// Returns the last write date and time, in coordinated universal time (UTC), of the specified file or directory.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which to obtain last write date and time information.
/// </param>
/// <returns>
/// A <see cref="DateTime" /> structure set to the last write date and time for the specified file or
/// directory. This value is expressed in UTC time.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static DateTime GetLastWriteTimeUtc(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetLastWriteTime(fileHandle).UtcDateTime;
}
public static FileAttributes GetAttributes(string path)
=> FileSystem.GetAttributes(Path.GetFullPath(path));
/// <summary>
/// Gets the specified <see cref="FileAttributes"/> of the file or directory associated to <paramref name="fileHandle"/>
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which the attributes are to be retrieved.
/// </param>
/// <returns>
/// The <see cref="FileAttributes"/> of the file or directory.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
public static FileAttributes GetAttributes(SafeFileHandle fileHandle)
{
ArgumentNullException.ThrowIfNull(fileHandle);
return FileSystem.GetAttributes(fileHandle);
}
public static void SetAttributes(string path, FileAttributes fileAttributes)
=> FileSystem.SetAttributes(Path.GetFullPath(path), fileAttributes);
/// <summary>
/// Sets the specified <see cref="FileAttributes"/> of the file or directory associated to <paramref name="fileHandle"/>.
/// </summary>
/// <param name="fileHandle">
/// A <see cref="SafeFileHandle" /> to the file or directory for which <paramref name="fileAttributes"/> should be set.
/// </param>
/// <param name="fileAttributes">
/// A bitwise combination of the enumeration values.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="fileHandle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// The caller does not have the required permission.
/// </exception>
/// <remarks>
/// It is not possible to change the compression status of a <see cref="File"/> object
/// using the <see cref="SetAttributes(SafeFileHandle, FileAttributes)"/> method.
/// </remarks>
public static void SetAttributes(SafeFileHandle fileHandle, FileAttributes fileAttributes)
{
ArgumentNullException.ThrowIfNull(fileHandle);
FileSystem.SetAttributes(fileHandle, fileAttributes);
}
/// <summary>Gets the <see cref="T:System.IO.UnixFileMode" /> of the file on the path.</summary>
/// <param name="path">The path to the file.</param>
/// <returns>The <see cref="T:System.IO.UnixFileMode" /> of the file on the path.</returns>
/// <exception cref="T:System.ArgumentException"><paramref name="path" /> is a zero-length string, or contains one or more invalid characters. You can query for invalid characters by using the <see cref="M:System.IO.Path.GetInvalidPathChars" /> method.</exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> is <see langword="null" />.</exception>
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="T:System.IO.PathTooLongException">The specified path exceeds the system-defined maximum length.</exception>
/// <exception cref="T:System.IO.DirectoryNotFoundException">A component of the <paramref name="path" /> is not a directory.</exception>
/// <exception cref="T:System.IO.FileNotFoundException">The file cannot be found.</exception>
[UnsupportedOSPlatform("windows")]
public static UnixFileMode GetUnixFileMode(string path)
=> GetUnixFileModeCore(path);
/// <summary>Gets the <see cref="T:System.IO.UnixFileMode" /> of the specified file handle.</summary>
/// <param name="fileHandle">The file handle.</param>
/// <returns>The <see cref="T:System.IO.UnixFileMode" /> of the file handle.</returns>
/// <exception cref="T:System.ObjectDisposedException">The file is closed.</exception>
[UnsupportedOSPlatform("windows")]
public static UnixFileMode GetUnixFileMode(SafeFileHandle fileHandle)
=> GetUnixFileModeCore(fileHandle);
/// <summary>Sets the specified <see cref="T:System.IO.UnixFileMode" /> of the file on the specified path.</summary>
/// <param name="path">The path to the file.</param>
/// <param name="mode">The unix file mode.</param>
/// <exception cref="T:System.ArgumentException"><paramref name="path" /> is a zero-length string, or contains one or more invalid characters. You can query for invalid characters by using the <see cref="M:System.IO.Path.GetInvalidPathChars" /> method.</exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> is <see langword="null" />.</exception>
/// <exception cref="T:System.ArgumentException">The caller attempts to use an invalid file mode.</exception>
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="T:System.IO.PathTooLongException">The specified path exceeds the system-defined maximum length.</exception>
/// <exception cref="T:System.IO.DirectoryNotFoundException">A component of the <paramref name="path" /> is not a directory.</exception>
/// <exception cref="T:System.IO.FileNotFoundException">The file cannot be found.</exception>
[UnsupportedOSPlatform("windows")]
public static void SetUnixFileMode(string path, UnixFileMode mode)
=> SetUnixFileModeCore(path, mode);
/// <summary>Sets the specified <see cref="T:System.IO.UnixFileMode" /> of the specified file handle.</summary>
/// <param name="fileHandle">The file handle.</param>
/// <param name="mode">The unix file mode.</param>
/// <exception cref="T:System.ArgumentException">The caller attempts to use an invalid file mode.</exception>
/// <exception cref="T:System.UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="T:System.ObjectDisposedException">The file is closed.</exception>
[UnsupportedOSPlatform("windows")]
public static void SetUnixFileMode(SafeFileHandle fileHandle, UnixFileMode mode)
=> SetUnixFileModeCore(fileHandle, mode);
public static FileStream OpenRead(string path)
=> new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
public static FileStream OpenWrite(string path)
=> new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
public static string ReadAllText(string path)
=> ReadAllText(path, Encoding.UTF8);
public static string ReadAllText(string path, Encoding encoding)
{
Validate(path, encoding);
using StreamReader sr = new StreamReader(path, encoding, detectEncodingFromByteOrderMarks: true);
return sr.ReadToEnd();
}
public static void WriteAllText(string path, string? contents)
=> WriteAllText(path, contents, UTF8NoBOM);
/// <summary>
/// Creates a new file, writes the specified string to the file, and then closes the file.
/// If the target file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The characters to write to the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// This method uses UTF-8 encoding without a Byte-Order Mark (BOM), so using the GetPreamble method will return an empty byte array. If it is necessary to
/// include a UTF-8 identifier, such as a byte order mark, at the beginning of a file, use the <see cref="WriteAllText(string, ReadOnlySpan{char}, Encoding)"/> method.
/// </remarks>
public static void WriteAllText(string path, ReadOnlySpan<char> contents)
=> WriteAllText(path, contents, UTF8NoBOM);
public static void WriteAllText(string path, string? contents, Encoding encoding)
{
Validate(path, encoding);
WriteToFile(path, FileMode.Create, contents, encoding);
}
/// <summary>
/// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file.
/// If the target file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="contents">The characters to write to the file.</param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="encoding"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
public static void WriteAllText(string path, ReadOnlySpan<char> contents, Encoding encoding)
{
Validate(path, encoding);
WriteToFile(path, FileMode.Create, contents, encoding);
}
public static byte[] ReadAllBytes(string path)
{
// SequentialScan is a perf hint that requires extra sys-call on non-Windows OSes.
FileOptions options = OperatingSystem.IsWindows() ? FileOptions.SequentialScan : FileOptions.None;
using (SafeFileHandle sfh = OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.Read, options))
{
long fileLength = 0;
if (sfh.CanSeek && (fileLength = sfh.GetFileLength()) > Array.MaxLength)
{
throw new IOException(SR.IO_FileTooLong2GB);
}
#if DEBUG
fileLength = 0; // improve the test coverage for ReadAllBytesUnknownLength
#endif
if (fileLength == 0)
{
// Some file systems (e.g. procfs on Linux) return 0 for length even when there's content; also there are non-seekable files.
// Thus we need to assume 0 doesn't mean empty.
return ReadAllBytesUnknownLength(sfh);
}
int index = 0;
int count = (int)fileLength;
byte[] bytes = new byte[count];
while (count > 0)
{
int n = RandomAccess.ReadAtOffset(sfh, bytes.AsSpan(index, count), index);
if (n == 0)
{
ThrowHelper.ThrowEndOfFileException();
}
index += n;
count -= n;
}
return bytes;
}
}
public static void WriteAllBytes(string path, byte[] bytes)
{
ArgumentNullException.ThrowIfNull(bytes);
WriteAllBytes(path, new ReadOnlySpan<byte>(bytes));
}
/// <summary>
/// Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="path">The file to write to.</param>
/// <param name="bytes">The bytes to write to the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
public static void WriteAllBytes(string path, ReadOnlySpan<byte> bytes)
{
ArgumentException.ThrowIfNullOrEmpty(path);
using SafeFileHandle sfh = OpenHandle(path, FileMode.Create, FileAccess.Write, FileShare.Read);
RandomAccess.WriteAtOffset(sfh, bytes, 0);
}
/// <summary>
/// Appends the specified byte array to the end of the file at the given path.
/// If the file doesn't exist, this method creates a new file.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="bytes">The bytes to append to the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="bytes"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
public static void AppendAllBytes(string path, byte[] bytes)
{
ArgumentNullException.ThrowIfNull(bytes);
AppendAllBytes(path, new ReadOnlySpan<byte>(bytes));
}
/// <summary>
/// Appends the specified byte array to the end of the file at the given path.
/// If the file doesn't exist, this method creates a new file.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="bytes">The bytes to append to the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
public static void AppendAllBytes(string path, ReadOnlySpan<byte> bytes)
{
ArgumentException.ThrowIfNullOrEmpty(path);
using SafeFileHandle fileHandle = OpenHandle(path, FileMode.Append, FileAccess.Write, FileShare.Read);
long fileOffset = RandomAccess.GetLength(fileHandle);
RandomAccess.WriteAtOffset(fileHandle, bytes, fileOffset);
}
/// <summary>
/// Asynchronously appends the specified byte array to the end of the file at the given path.
/// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="bytes">The bytes to append to the file.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous append operation.</returns>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="bytes"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="OperationCanceledException">The cancellation token was canceled. This exception is stored into the returned task.</exception>
public static Task AppendAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(bytes);
return AppendAllBytesAsync(path, new ReadOnlyMemory<byte>(bytes), cancellationToken);
}
/// <summary>
/// Asynchronously appends the specified byte array to the end of the file at the given path.
/// If the file doesn't exist, this method creates a new file. If the operation is canceled, the task will return in a canceled state.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="bytes">The bytes to append to the file.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous append operation.</returns>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="OperationCanceledException">The cancellation token was canceled. This exception is stored into the returned task.</exception>
public static Task AppendAllBytesAsync(string path, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrEmpty(path);
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: Core(path, bytes, cancellationToken);
static async Task Core(string path, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken)
{
using SafeFileHandle fileHandle = OpenHandle(path, FileMode.Append, FileAccess.Write, FileShare.Read, FileOptions.Asynchronous);
long fileOffset = RandomAccess.GetLength(fileHandle);
await RandomAccess.WriteAtOffsetAsync(fileHandle, bytes, fileOffset, cancellationToken).ConfigureAwait(false);
}
}
public static string[] ReadAllLines(string path)
=> ReadAllLines(path, Encoding.UTF8);
public static string[] ReadAllLines(string path, Encoding encoding)
{
Validate(path, encoding);
string? line;
List<string> lines = new List<string>();
using StreamReader sr = new StreamReader(path, encoding);
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
return lines.ToArray();
}
public static IEnumerable<string> ReadLines(string path)
=> ReadLines(path, Encoding.UTF8);
public static IEnumerable<string> ReadLines(string path, Encoding encoding)
{
Validate(path, encoding);
return ReadLinesIterator.CreateIterator(path, encoding);
}
/// <summary>
/// Asynchronously reads the lines of a file.
/// </summary>
/// <param name="path">The file to read.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>The async enumerable that represents all the lines of the file, or the lines that are the result of a query.</returns>
public static IAsyncEnumerable<string> ReadLinesAsync(string path, CancellationToken cancellationToken = default)
=> ReadLinesAsync(path, Encoding.UTF8, cancellationToken);
/// <summary>
/// Asynchronously reads the lines of a file that has a specified encoding.
/// </summary>
/// <param name="path">The file to read.</param>
/// <param name="encoding">The encoding that is applied to the contents of the file.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>The async enumerable that represents all the lines of the file, or the lines that are the result of a query.</returns>
public static IAsyncEnumerable<string> ReadLinesAsync(string path, Encoding encoding, CancellationToken cancellationToken = default)
{
Validate(path, encoding);
StreamReader sr = AsyncStreamReader(path, encoding); // Move first streamReader allocation here so to throw related file exception upfront, which will cause known leaking if user never actually foreach's over the enumerable
return IterateFileLinesAsync(sr, path, encoding, cancellationToken);
}
public static void WriteAllLines(string path, string[] contents)
=> WriteAllLines(path, (IEnumerable<string>)contents);
public static void WriteAllLines(string path, IEnumerable<string> contents)
=> WriteAllLines(path, contents, UTF8NoBOM);
public static void WriteAllLines(string path, string[] contents, Encoding encoding)
=> WriteAllLines(path, (IEnumerable<string>)contents, encoding);
public static void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
{
Validate(path, encoding);
ArgumentNullException.ThrowIfNull(contents);
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
private static void InternalWriteAllLines(StreamWriter writer, IEnumerable<string> contents)
{
Debug.Assert(writer != null);
Debug.Assert(contents != null);
using (writer)
{
foreach (string line in contents)
{
writer.WriteLine(line);
}
}
}
public static void AppendAllText(string path, string? contents)
=> AppendAllText(path, contents, UTF8NoBOM);
/// <summary>
/// Appends the specified string to the file, creating the file if it does not already exist.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="contents">The characters to write to the file.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// Given a string and a file path, this method opens the specified file, appends the string to the end of the file using the specified encoding,
/// and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised. The method creates the file
/// if it doesn't exist, but it doesn't create new directories. Therefore, the value of the path parameter must contain existing directories.
/// </remarks>
public static void AppendAllText(string path, ReadOnlySpan<char> contents)
=> AppendAllText(path, contents, UTF8NoBOM);
public static void AppendAllText(string path, string? contents, Encoding encoding)
{
Validate(path, encoding);
WriteToFile(path, FileMode.Append, contents, encoding);
}
/// <summary>
/// Appends the specified string to the file, creating the file if it does not already exist.
/// </summary>
/// <param name="path">The file to append to.</param>
/// <param name="contents">The characters to write to the file.</param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="path"/> is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="encoding"/> is <see langword="null"/>.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is read-only.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a file that is hidden.</exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path"/> specified a directory.</exception>
/// <exception cref="UnauthorizedAccessException">This operation is not supported on the current platform.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="NotSupportedException"><paramref name="path"/> is in an invalid format.</exception>
/// <remarks>
/// Given a string and a file path, this method opens the specified file, appends the string to the end of the file using the specified encoding,