-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
ZipArchiveFileSystem.cs
1042 lines (893 loc) · 33.7 KB
/
ZipArchiveFileSystem.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
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading;
#if HAS_ZIPARCHIVE
namespace Zio.FileSystems;
/// <summary>
/// Provides a <see cref="IFileSystem" /> for the ZipArchive filesystem.
/// </summary>
public class ZipArchiveFileSystem : FileSystem
{
private readonly bool _isCaseSensitive;
private readonly ZipArchive _archive;
private readonly CompressionLevel _compressionLevel;
private readonly ReaderWriterLockSlim _entriesLock = new();
private FileSystemEventDispatcher<FileSystemWatcher>? _dispatcher;
private readonly object _dispatcherLock = new();
private readonly DateTime _creationTime;
private readonly Dictionary<string, ZipArchiveEntry> _entries;
private readonly Dictionary<ZipArchiveEntry, EntryState> _openStreams;
private readonly object _openStreamsLock = new();
#if NETFRAMEWORK // .Net4.5 uses a backslash as directory separator
private const char DirectorySeparator = '\\';
#else
private const char DirectorySeparator = '/';
#endif
/// <summary>
/// Initializes a new instance of the <see cref="ZipArchiveFileSystem" /> class.
/// </summary>
/// <param name="archive">An instance of <see cref="ZipArchive" /></param>
/// <param name="isCaseSensitive">Specifies if entry names should be case sensitive</param>
/// <exception cref="ArgumentNullException"></exception>
public ZipArchiveFileSystem(ZipArchive archive, bool isCaseSensitive = false, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
{
_archive = archive;
_isCaseSensitive = isCaseSensitive;
_creationTime = DateTime.Now;
_compressionLevel = compressionLevel;
if (archive == null)
{
throw new ArgumentNullException(nameof(archive));
}
#if NETFRAMEWORK // .Net4.5 uses a backslash as directory separator
foreach (var entry in _archive.Entries)
{
entry.FullName.Replace('/', DirectorySeparator);
}
#else
foreach (var entry in _archive.Entries)
{
entry.FullName.Replace('\\', DirectorySeparator);
}
#endif
if (!_isCaseSensitive)
{
_entries = _archive.Entries.ToDictionary(e => e.FullName.ToLowerInvariant(), e => e);
}
_openStreams = new Dictionary<ZipArchiveEntry, EntryState>();
}
/// <summary>
/// Initializes a new instance of the <see cref="ZipArchiveFileSystem" /> class.
/// </summary>
/// <param name="stream">Instance of stream to create <see cref="ZipArchive" /> from</param>
/// <param name="mode">Mode of <see cref="ZipArchive" /></param>
/// <param name="leaveOpen">True to leave the stream open when <see cref="ZipArchive" /> is disposed</param>
/// <param name="isCaseSensitive"></param>
public ZipArchiveFileSystem(Stream stream, ZipArchiveMode mode = ZipArchiveMode.Update, bool leaveOpen = false, bool isCaseSensitive = false, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
: this(new ZipArchive(stream, mode, leaveOpen), isCaseSensitive, compressionLevel)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZipArchiveFileSystem" /> class from file.
/// </summary>
/// <param name="path">Path to zip file</param>
/// <param name="mode">Mode of <see cref="ZipArchive" /></param>
/// <param name="leaveOpen">True to leave the stream open when <see cref="ZipArchive" /> is disposed</param>
/// <param name="isCaseSensitive">Specifies if entry names should be case sensitive</param>
public ZipArchiveFileSystem(string path, ZipArchiveMode mode = ZipArchiveMode.Update, bool leaveOpen = false, bool isCaseSensitive = false, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
: this(new ZipArchive(File.Open(path, FileMode.OpenOrCreate), mode, leaveOpen), isCaseSensitive, compressionLevel)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZipArchiveFileSystem" /> class with a <see cref="MemoryStream" />
/// </summary>
/// <param name="mode">Mode of <see cref="ZipArchive" /></param>
/// <param name="leaveOpen">True to leave the stream open when <see cref="ZipArchive" /> is disposed</param>
/// <param name="isCaseSensitive">Specifies if entry names should be case sensitive</param>
public ZipArchiveFileSystem(ZipArchiveMode mode = ZipArchiveMode.Update, bool leaveOpen = false, bool isCaseSensitive = false, CompressionLevel compressionLevel = CompressionLevel.NoCompression)
: this(new ZipArchive(new MemoryStream(), mode, leaveOpen), isCaseSensitive, compressionLevel)
{
}
private ZipArchiveEntry? GetEntry(string path)
{
#if NETFRAMEWORK
path = path.Replace('/', DirectorySeparator);
#else
path = path.Replace('\\', DirectorySeparator);
#endif
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
path = RemoveLeadingSlash(path);
_entriesLock.EnterReadLock();
try
{
if (_isCaseSensitive)
{
return _archive.GetEntry(path);
}
return _entries.TryGetValue(path.ToLowerInvariant(), out var foundEntry) ? foundEntry : null;
}
finally
{
_entriesLock.ExitReadLock();
}
}
/// <inheritdoc />
protected override UPath ConvertPathFromInternalImpl(string innerPath)
{
return new UPath(innerPath);
}
/// <inheritdoc />
protected override string ConvertPathToInternalImpl(UPath path)
{
return path.FullName;
}
/// <inheritdoc />
protected override void CopyFileImpl(UPath srcPath, UPath destPath, bool overwrite)
{
if (srcPath == destPath)
{
throw new IOException("Source and destination path must be different.");
}
var srcEntry = GetEntry(srcPath.FullName);
if (srcEntry == null)
{
if (DirectoryExistsImpl(srcPath))
{
throw new UnauthorizedAccessException(nameof(srcPath) + " is a directory.");
}
if (!DirectoryExistsImpl(srcPath.GetDirectory()))
{
throw new DirectoryNotFoundException(srcPath.GetDirectory().FullName);
}
throw FileSystemExceptionHelper.NewFileNotFoundException(srcPath);
}
var parentDirectory = destPath.GetDirectory();
if (!DirectoryExistsImpl(parentDirectory))
{
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(parentDirectory);
}
if (DirectoryExistsImpl(destPath))
{
if (!FileExistsImpl(destPath))
{
throw new IOException("Destination path is a directory");
}
}
var destEntry = GetEntry(destPath.FullName);
if (destEntry != null)
{
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
if ((destEntry.ExternalAttributes & (int)FileAttributes.ReadOnly) == (int)FileAttributes.ReadOnly)
{
throw new UnauthorizedAccessException("Destination file is read only");
}
#endif
if (!overwrite)
{
throw FileSystemExceptionHelper.NewDestinationFileExistException(srcPath);
}
RemoveEntry(destEntry);
TryGetDispatcher()?.RaiseDeleted(destPath);
}
destEntry = CreateEntry(destPath.FullName);
using (var destStream = destEntry.Open())
{
using var srcStream = srcEntry.Open();
srcStream.CopyTo(destStream);
}
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
destEntry.ExternalAttributes = srcEntry.ExternalAttributes | (int)FileAttributes.Archive;
#endif
TryGetDispatcher()?.RaiseCreated(destPath);
}
/// <inheritdoc />
protected override void CreateDirectoryImpl(UPath path)
{
if (FileExistsImpl(path))
{
throw FileSystemExceptionHelper.NewDestinationFileExistException(path);
}
if (DirectoryExistsImpl(path))
{
throw FileSystemExceptionHelper.NewDestinationDirectoryExistException(path);
}
var parentPath = new UPath(GetParent(path.FullName));
if (parentPath != "")
{
if (!DirectoryExistsImpl(parentPath))
{
CreateDirectoryImpl(parentPath);
}
}
var entryPath = RemoveLeadingSlash(path);
#if NETFRAMEWORK
entryPath = entryPath.Replace('/', DirectorySeparator);
#else
entryPath = entryPath.Replace('\\', DirectorySeparator);
#endif
CreateEntry(ConvertPathToDirectory(entryPath));
TryGetDispatcher()?.RaiseCreated(entryPath);
}
/// <inheritdoc />
protected override void DeleteDirectoryImpl(UPath path, bool isRecursive)
{
var entryPath = RemoveLeadingSlash(ConvertPathToDirectory(path));
#if NETFRAMEWORK
entryPath = entryPath.Replace('/', DirectorySeparator);
#else
entryPath = entryPath.Replace('\\', DirectorySeparator);
#endif
var entries = new List<ZipArchiveEntry>();
if (!isRecursive)
{
// folder name ends with slash so StartWith check is enough
_entriesLock.EnterReadLock();
try
{
entries = _archive.Entries.Where(x => x.FullName.StartsWith(entryPath, _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)).Take(2).ToList();
}
finally
{
_entriesLock.ExitReadLock();
}
if (entries.Count == 0)
{
if (FileExistsImpl(path))
{
throw new IOException($"{path} is a file");
}
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(path);
}
if (entries.Count == 1)
{
RemoveEntry(entries[0]);
}
if (entries.Count == 2)
{
throw new IOException("Directory is not empty");
}
TryGetDispatcher()?.RaiseDeleted(path);
return;
}
_entriesLock.EnterReadLock();
try
{
entries = _archive.Entries.Where(x => x.FullName.StartsWith(entryPath, _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)).ToList();
if (entries.Count == 0)
{
entryPath = entryPath.Substring(0, entryPath.Length - 1);
if (_isCaseSensitive ? _archive.GetEntry(entryPath) != null : _entries.ContainsKey(entryPath.ToLowerInvariant()))
{
throw new IOException($"{path} is a file");
}
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(path);
}
// check if there are no open file in directory
foreach (var entry in entries)
{
lock (_openStreamsLock)
{
if (_openStreams.ContainsKey(entry))
{
throw new IOException($"There is an open file {entry.FullName} in directory");
}
}
}
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
// check if there are none readonly entries
foreach (var entry in entries)
{
if ((entry.ExternalAttributes & (int)FileAttributes.ReadOnly) == (int)FileAttributes.ReadOnly)
{
throw entry.FullName == entryPath
? new IOException("Directory is read only")
: new UnauthorizedAccessException($"Cannot delete directory that contains readonly entry {entry.FullName}");
}
}
#endif
}
finally
{
_entriesLock.ExitReadLock();
}
_entriesLock.EnterWriteLock();
try
{
foreach (var entry in entries)
{
entry.Delete();
if (!_isCaseSensitive)
{
_entries.Remove(entry.FullName.ToLowerInvariant());
}
}
}
finally
{
_entriesLock.ExitWriteLock();
}
TryGetDispatcher()?.RaiseDeleted(path);
}
/// <inheritdoc />
protected override void DeleteFileImpl(UPath path)
{
if (DirectoryExistsImpl(path))
{
throw new IOException("Cannot delete a directory");
}
var entry = GetEntry(path.FullName);
if (entry == null)
{
return;
}
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
if ((entry.ExternalAttributes & (int)FileAttributes.ReadOnly) == (int)FileAttributes.ReadOnly)
{
throw new UnauthorizedAccessException("Cannot delete file with readonly attribute");
}
#endif
TryGetDispatcher()?.RaiseDeleted(path);
RemoveEntry(entry);
}
/// <inheritdoc />
protected override bool DirectoryExistsImpl(UPath path)
{
if (path.FullName is "/" or "\\" or "")
{
return true;
}
return GetEntry(ConvertPathToDirectory(path.FullName)) != null;
}
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
_archive.Dispose();
if (disposing)
{
TryGetDispatcher()?.Dispose();
}
}
/// <inheritdoc />
protected override IEnumerable<FileSystemItem> EnumerateItemsImpl(UPath path, SearchOption searchOption, SearchPredicate? searchPredicate)
{
return EnumeratePathsStr(path, "*", searchOption, SearchTarget.Both).Select(p => new FileSystemItem(this, p, p[p.Length - 1] == DirectorySeparator));
}
/// <inheritdoc />
protected override IEnumerable<UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return EnumeratePathsStr(path, searchPattern, searchOption, searchTarget).Select(x => new UPath(x));
}
private IEnumerable<string> EnumeratePathsStr(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
var search = SearchPattern.Parse(ref path, ref searchPattern);
var entryPath = RemoveLeadingSlash(path);
var root = ConvertPathToDirectory(entryPath);
#if NETFRAMEWORK
root = root.Replace('/', '\\');
#else
root = root.Replace('\\', '/');
#endif
_entriesLock.EnterReadLock();
var entriesList = new List<ZipArchiveEntry>();
try
{
entriesList = root == ""
? _archive.Entries.ToList()
: _archive.Entries.Where(e => e.FullName.StartsWith(root, _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) && e.FullName.Length > root.Length).ToList();
}
finally
{
_entriesLock.ExitReadLock();
}
if (entriesList.Count == 0)
{
return Enumerable.Empty<string>();
}
var entries = (IEnumerable<ZipArchiveEntry>)entriesList;
if (searchOption == SearchOption.TopDirectoryOnly)
{
var dir = GetParent(entries.First().FullName);
entries = entries.Where(e => string.Equals(ConvertPathToDirectory(GetParent(e.FullName)), root, _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));
}
if (searchTarget == SearchTarget.File)
{
entries = entries.Where(e => e.FullName[e.FullName.Length - 1] != DirectorySeparator);
}
else if (searchTarget == SearchTarget.Directory)
{
entries = entries.Where(e => e.FullName[e.FullName.Length - 1] == DirectorySeparator);
}
if (!string.IsNullOrEmpty(searchPattern))
{
entries = entries.Where(e => search.Match(GetName(e)));
}
return entries.Select(e => '/' + e.FullName);
}
/// <inheritdoc />
protected override bool FileExistsImpl(UPath path)
{
return GetEntry(path.FullName) != null;
}
/// <inheritdoc />
protected override FileAttributes GetAttributesImpl(UPath path)
{
var entry = GetEntry(path.FullName) ?? GetEntry(ConvertPathToDirectory(path));
if (entry is null)
{
throw FileSystemExceptionHelper.NewFileNotFoundException(path);
}
var attributes = entry.FullName[entry.FullName.Length - 1] == DirectorySeparator ? FileAttributes.Directory : 0;
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
if (entry.ExternalAttributes == 0 && attributes == 0)
{
attributes |= FileAttributes.Normal;
}
return (FileAttributes)entry.ExternalAttributes | attributes;
#endif
// return standard attributes if it's not NetStandard2.1
return attributes == FileAttributes.Directory ? FileAttributes.Directory : entry.LastWriteTime >= _creationTime ? FileAttributes.Archive : FileAttributes.Normal;
}
/// <inheritdoc />
protected override long GetFileLengthImpl(UPath path)
{
var entry = GetEntry(path.FullName);
if (entry == null)
{
throw FileSystemExceptionHelper.NewFileNotFoundException(path);
}
try
{
return entry.Length;
}
catch (Exception ex) // for some reason entry.Length doesn't work with MemoryStream used in tests
{
Debug.WriteLine(ex.Message);
using var stream = OpenFileImpl(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return stream.Length;
}
}
/// <summary>
/// Not supported by zip format. Return last write time.
/// </summary>
protected override DateTime GetCreationTimeImpl(UPath path)
{
return GetLastWriteTimeImpl(path);
}
/// <summary>
/// Not supported by zip format. Return last write time
/// </summary>
protected override DateTime GetLastAccessTimeImpl(UPath path)
{
return GetLastWriteTimeImpl(path);
}
/// <inheritdoc />
protected override DateTime GetLastWriteTimeImpl(UPath path)
{
var entry = GetEntry(path.FullName) ?? GetEntry(ConvertPathToDirectory(path));
if (entry == null)
{
return DefaultFileTime;
}
return entry.LastWriteTime.DateTime;
}
/// <inheritdoc />
protected override void MoveDirectoryImpl(UPath srcPath, UPath destPath)
{
if (destPath.IsInDirectory(srcPath, true))
{
throw new IOException("Cannot move directory to itself or a subdirectory.");
}
var srcDir = RemoveLeadingSlash(ConvertPathToDirectory(srcPath.FullName));
var destDir = RemoveLeadingSlash(ConvertPathToDirectory(destPath.FullName));
#if NETFRAMEWORK
srcDir = srcDir.Replace('/', DirectorySeparator);
destDir = destDir.Replace('/', DirectorySeparator);
#else
srcDir = srcDir.Replace('\\', DirectorySeparator);
destDir = destDir.Replace('\\', DirectorySeparator);
#endif
_entriesLock.EnterReadLock();
var entries = Array.Empty<ZipArchiveEntry>();
try
{
entries = _archive.Entries.Where(e => e.FullName.StartsWith(srcDir, _isCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)).ToArray();
}
finally
{
_entriesLock.ExitReadLock();
}
if (entries.Length == 0)
{
if (FileExistsImpl(srcPath))
{
throw new IOException(nameof(srcPath) + " is a file.");
}
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(srcPath);
}
CreateDirectoryImpl(destPath);
foreach (var entry in entries)
{
if (entry.FullName.Length == srcDir.Length)
{
RemoveEntry(entry);
continue;
}
using (var entryStream = entry.Open())
{
var entryName = entry.FullName.Substring(srcDir.Length);
var destEntry = CreateEntry(destDir + entryName);
using (var destEntryStream = destEntry.Open())
{
entryStream.CopyTo(destEntryStream);
}
}
TryGetDispatcher()?.RaiseCreated(destPath);
RemoveEntry(entry);
TryGetDispatcher()?.RaiseDeleted(srcPath);
}
}
/// <inheritdoc />
protected override void MoveFileImpl(UPath srcPath, UPath destPath)
{
var srcEntry = GetEntry(srcPath.FullName) ?? throw FileSystemExceptionHelper.NewFileNotFoundException(srcPath);
if (!DirectoryExistsImpl(destPath.GetDirectory()))
{
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(destPath.GetDirectory());
}
var destEntry = GetEntry(destPath.FullName);
if (destEntry != null)
{
throw new IOException("Cannot overwrite existing file.");
}
destEntry = CreateEntry(destPath.FullName);
TryGetDispatcher()?.RaiseCreated(destPath);
using (var destStream = destEntry.Open())
{
using var srcStream = srcEntry.Open();
srcStream.CopyTo(destStream);
}
RemoveEntry(srcEntry);
TryGetDispatcher()?.RaiseDeleted(srcPath);
}
/// <inheritdoc />
protected override Stream OpenFileImpl(UPath path, FileMode mode, FileAccess access, FileShare share)
{
if (_archive.Mode == ZipArchiveMode.Read && access == FileAccess.Write)
{
throw new UnauthorizedAccessException("Cannot open a file for writing in a read-only archive.");
}
if (access == FileAccess.Read && (mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Truncate || mode == FileMode.Append))
{
throw new ArgumentException("Cannot write in a read-only access.");
}
var entry = GetEntry(path.FullName);
if (entry == null)
{
if (mode is FileMode.Create or FileMode.CreateNew or FileMode.OpenOrCreate or FileMode.Append)
{
entry = CreateEntry(path.FullName);
#if NETSTANDARD2_1
entry.ExternalAttributes = (int)FileAttributes.Archive;
#endif
TryGetDispatcher()?.RaiseCreated(path);
}
else
{
if (DirectoryExistsImpl(path))
{
throw new UnauthorizedAccessException(nameof(path) + " is a directory.");
}
if (!DirectoryExistsImpl(path.GetDirectory()))
{
throw FileSystemExceptionHelper.NewDirectoryNotFoundException(path.GetDirectory());
}
throw FileSystemExceptionHelper.NewFileNotFoundException(path);
}
}
else if (mode == FileMode.CreateNew)
{
throw new IOException("Cannot create a file in CreateNew mode if it already exists.");
}
else if (mode == FileMode.Create)
{
RemoveEntry(entry);
entry = CreateEntry(path.FullName);
}
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
if ((access == FileAccess.Write || access == FileAccess.ReadWrite) && (entry.ExternalAttributes & (int)FileAttributes.ReadOnly) == (int)FileAttributes.ReadOnly)
{
throw new UnauthorizedAccessException("Cannot open a file for writing in a file with readonly attribute.");
}
#endif
var stream = new ZipEntryStream(share, this, entry);
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
if (access is FileAccess.Write or FileAccess.ReadWrite)
{
entry.ExternalAttributes |= (int)FileAttributes.Archive;
}
#endif
if (mode == FileMode.Append)
{
stream.Seek(0, SeekOrigin.End);
}
else if (mode == FileMode.Truncate)
{
stream.SetLength(0);
}
return stream;
}
/// <inheritdoc />
protected override void ReplaceFileImpl(UPath srcPath, UPath destPath, UPath destBackupPath, bool ignoreMetadataErrors)
{
var sourceEntry = GetEntry(srcPath.FullName);
if (sourceEntry is null)
{
throw FileSystemExceptionHelper.NewFileNotFoundException(srcPath);
}
var destEntry = GetEntry(destPath.FullName);
if (destEntry == sourceEntry)
{
throw new IOException("Cannot replace the file with itself.");
}
if (destEntry != null)
{
// create a backup at destBackupPath if its not null
if (destBackupPath != null)
{
var destBackupEntry = CreateEntry(destBackupPath.FullName);
using var destBackupStream = destBackupEntry.Open();
using var destStream = destEntry.Open();
destStream.CopyTo(destBackupStream);
}
RemoveEntry(destEntry);
}
var newEntry = CreateEntry(destPath.FullName);
using (var newStream = newEntry.Open())
{
using (var sourceStream = sourceEntry.Open())
{
sourceStream.CopyTo(newStream);
}
}
RemoveEntry(sourceEntry);
TryGetDispatcher()?.RaiseDeleted(srcPath);
TryGetDispatcher()?.RaiseCreated(destPath);
}
/// <summary>
/// Implementation for <see cref="SetAttributes" />, <paramref name="path" /> is guaranteed to be absolute and
/// validated through <see cref="ValidatePath" />. Works only in Net Standard 2.1
/// Sets the specified <see cref="FileAttributes" /> of the file or directory on the specified path.
/// </summary>
/// <param name="path">The path to the file or directory.</param>
/// <param name="attributes">A bitwise combination of the enumeration values.</param>
protected override void SetAttributesImpl(UPath path, FileAttributes attributes)
{
#if NETSTANDARD2_1_OR_GREATER || NET6_0_OR_GREATER
var entryPath = RemoveLeadingSlash(path);
var entry = GetEntry(entryPath) ?? GetEntry(ConvertPathToDirectory(entryPath));
if (entry == null)
{
throw FileSystemExceptionHelper.NewFileNotFoundException(path);
}
entry.ExternalAttributes = (int)attributes;
TryGetDispatcher()?.RaiseChange(path);
return;
#endif
Debug.WriteLine("SetAttributes don't work in NetStandard2.0 or older.");
}
/// <summary>
/// Not supported by zip format. Does nothing.
/// </summary>
protected override void SetCreationTimeImpl(UPath path, DateTime time)
{
}
/// <summary>
/// Not supported by zip format. Does nothing.
/// </summary>
protected override void SetLastAccessTimeImpl(UPath path, DateTime time)
{
}
/// <inheritdoc />
protected override void SetLastWriteTimeImpl(UPath path, DateTime time)
{
var entry = GetEntry(path.FullName) ?? GetEntry(ConvertPathToDirectory(path.FullName));
if (entry is null)
{
throw FileSystemExceptionHelper.NewFileNotFoundException(path);
}
TryGetDispatcher()?.RaiseChange(path);
entry.LastWriteTime = time;
}
/// <inheritdoc />
protected override IFileSystemWatcher WatchImpl(UPath path)
{
var watcher = new FileSystemWatcher(this, path);
lock (_dispatcherLock)
{
_dispatcher ??= new FileSystemEventDispatcher<FileSystemWatcher>(this);
_dispatcher.Add(watcher);
}
return watcher;
}
private void RemoveEntry(ZipArchiveEntry entry)
{
_entriesLock.EnterWriteLock();
try
{
entry.Delete();
if (!_isCaseSensitive)
{
_entries.Remove(entry.FullName.ToLowerInvariant());
}
}
finally
{
_entriesLock.ExitWriteLock();
}
}
private ZipArchiveEntry CreateEntry(string path)
{
path = RemoveLeadingSlash(path);
#if NETFRAMEWORK
path = path.Replace('/', DirectorySeparator);
#else
path = path.Replace('\\', DirectorySeparator);
#endif
_entriesLock.EnterWriteLock();
try
{
var entry = _archive.CreateEntry(path, _compressionLevel);
if (!_isCaseSensitive)
{
_entries.Add(entry.FullName.ToLowerInvariant(), entry);
}
return entry;
}
finally
{
_entriesLock.ExitWriteLock();
}
}
private static readonly char[] s_slashChars = { '/', '\\' };
private static string GetName(ZipArchiveEntry entry)
{
var name = entry.FullName.TrimEnd(s_slashChars);
var index = name.LastIndexOfAny(s_slashChars);
return name.Substring(index + 1);
}
private static string GetParent(string path)
{
path = path.TrimEnd(s_slashChars);
var lastIndex = path.LastIndexOfAny(s_slashChars);
return lastIndex == -1 ? "" : path.Substring(0, lastIndex);
}
private static string ConvertPathToDirectory(UPath path)
{
return ConvertPathToDirectory(path.FullName);
}
private static string ConvertPathToDirectory(string path)
{
if (string.IsNullOrEmpty(path))
{
return path;
}
return path[path.Length - 1] is DirectorySeparator ? path : path + DirectorySeparator;
}
private static string RemoveLeadingSlash(UPath path)
{
return path.FullName[0] is '\\' or '/' ? path.FullName.Substring(1) : path.FullName;
}
private static string RemoveLeadingSlash(string path)
{
return path[0] is '\\' or '/' ? path.Substring(1) : path;
}
private FileSystemEventDispatcher<FileSystemWatcher>? TryGetDispatcher()
{
lock (_dispatcherLock)
{
return _dispatcher;
}
}
private sealed class ZipEntryStream : Stream
{
private readonly ZipArchiveEntry _entry;
private readonly ZipArchiveFileSystem _fileSystem;
private readonly Stream _streamImplementation;
private bool _isDisposed;
public ZipEntryStream(FileShare share, ZipArchiveFileSystem system, ZipArchiveEntry entry)
{
_entry = entry;
_fileSystem = system;
lock (_fileSystem._openStreamsLock)
{
var fileShare = _fileSystem._openStreams.TryGetValue(entry, out var fileData) ? fileData.Share : FileShare.ReadWrite;
if (fileData != null)
{
// we only check for read share, because ZipArchive doesn't support write share
if (share is not FileShare.Read and not FileShare.ReadWrite)
{
throw new IOException("File is already opened for reading");
}
if (fileShare is not FileShare.Read and not FileShare.ReadWrite)
{
throw new IOException("File is already opened for reading by another stream with non compatible share");
}
fileData.Count++;
}
else
{
_fileSystem._openStreams.Add(_entry, new EntryState(share));
}
_streamImplementation = entry.Open();
}
Share = share;
}
private FileShare Share { get; }
public override bool CanRead => _streamImplementation.CanRead;
public override bool CanSeek => _streamImplementation.CanSeek;
public override bool CanWrite => _streamImplementation.CanWrite;
public override long Length => _streamImplementation.Length;
public override long Position
{
get => _streamImplementation.Position;
set => _streamImplementation.Position = value;
}
public override void Flush()
{
_streamImplementation.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _streamImplementation.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _streamImplementation.Seek(offset, origin);
}
public override void SetLength(long value)
{
_streamImplementation.SetLength(value);
}