public Stream IncreaseSize(int value, out long offset) { lock (_lock) { while (Interlocked.Read(ref _counter) != 0) { if (!Monitor.Wait(_lock, 10000, true)) throw new NotSupportedException(); } FileStream file = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); try { offset = MathEx.RoundUp(file.Length, 0x800); file.SetLength(offset + value); _mmf = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.Inheritable, false); } catch { file.SafeDispose(); throw; } Interlocked.Increment(ref _counter); DisposableStream result = new DisposableStream(_mmf.CreateViewStream(offset, value, MemoryMappedFileAccess.ReadWrite)); result.AfterDispose.Add(new DisposableAction(Free)); return result; } }
public static void Unzip(string targetDirectoryPath, ZipArchive archive) { foreach (var zipEntry in archive.Entries) { var outFilePath = Path.Combine(targetDirectoryPath, zipEntry.FullName); var outFileInfo = new FileInfo(outFilePath); if (!outFileInfo.Directory.Exists) { outFileInfo.Directory.Create(); } Stream outFileStream = null; Stream inputStream = null; try { outFileStream = new FileStream( outFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); inputStream = zipEntry.Open(); inputStream.CopyTo(outFileStream); } finally { outFileStream.SafeDispose(); inputStream.SafeDispose(); } } }
private static void Verify(string filePath, byte[] expectedHash, string hashName) { HashAlgorithm hashAlgorithm = null; Stream inputStream = null; try { hashAlgorithm = HashAlgorithm.Create(hashName); inputStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.None); var readBuffer = new byte[StreamReadBufferSize]; int bytesRead; while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0) { hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0); } hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0); var isHashMatches = hashAlgorithm.Hash.SequenceEqual(expectedHash); if (!isHashMatches) { var expectedHashString = GetHexString(expectedHash); var actualHashString = GetHexString(hashAlgorithm.Hash); throw new Exception( $"Checksum for {filePath} does not match. Expected: {expectedHashString}, Actual: {actualHashString}"); } } finally { inputStream.SafeDispose(); hashAlgorithm.SafeDispose(); } }