Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Last active May 9, 2022 08:21
Show Gist options
  • Save Sl4vP0weR/41b561f97a5e99bf960f16a09ebfd6a1 to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/41b561f97a5e99bf960f16a09ebfd6a1 to your computer and use it in GitHub Desktop.
FileStream that not consuming too much memory to read/write.
/// <summary>
/// FileStream that not consuming too much memory to read/write.
/// </summary>
public class LazyFileStream :
FileStream, IDisposable
{
public LazyFileStream(string path, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.ReadWrite, int buffer = 4096, FileOptions options = FileOptions.SequentialScan | FileOptions.Asynchronous) : base(path, mode, access, share, buffer, options)
{ }
public void Write(byte[] data, int offset = 0)
{
Write(data, offset, data.Length);
}
public byte[] Read(Range range) => Read(range.End.Value - range.Start.Value, range.Start.Value);
public byte[] Read(int length, int offset = -1)
{
var buffer = new byte[length];
if(offset >= 0) Position = offset;
Read(buffer, 0, buffer.Length);
return buffer;
}
/// <summary>
/// Dispose this instance and write all changes
/// </summary>
public new void Dispose() => base.Dispose();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment