C#创建一个带偏移量的FileStream

时间:2015-06-26 17:09:25

标签: c# file-io zip

问题

有没有办法用C#在C#中创建FileStream?例如,如果我在偏移100处打开 SomeFile.bin Stream.Position将等于0,但是读取&写入将被100偏移。

背景

我正在为我的公司开发混合文件格式,它将机器可读的二进制数据与现代PC可读的OPC文件(本质上是使用System.IO.Packaging创建的ZIP文件)相结合。出于性能原因,二进制数据必须出现在文件的顶部。我了解ZIP文件将允许此操作(例如自解压缩档案),但不幸的是内部ZipIOCentralDirectoryBlock类是hard-coded to reject ZIP files where the first file header doesn't appear at offset 0。为了避免临时文件(因为文件可能大到3.99GB),我想欺骗ZipPackage认为它处理文件的开头,而实际上它是&# 39;阅读&写在偏移处。

1 个答案:

答案 0 :(得分:3)

不确定。这是装饰器模式的完美案例:

基本上你创建了一个

的类
  • 继承自Stream(您正在装饰的抽象类)
  • 有一个构造函数,它接受该基类的单个实例

然后覆盖所有方法和属性,将调用传递给修饰实例。如果方法或属性知道流的位置或长度,则根据需要应用适当的调整。

编辑注意: 看起来您需要装饰抽象流,如下所示(无法在不实际打开文件的情况下创建文件流实例)。

这是装饰器本身的[截断]示例:

class OffsetStreamDecorator : Stream
{
  private readonly Stream instance ;
  private readonly long       offset   ;

  public static Stream Decorate( Stream instance )
  {
    if ( instance == null ) throw new ArgumentNullException("instance") ;

    FileStream decorator= new OffsetStreamDecorator( instance ) ;
    return decorator;
  }

  private OffsetStreamDecorator( FileStream instance )
  {
    this.instance = instance ;
    this.offset   = instance.Position ;
  }

  #region override methods and properties pertaining to the file position/length to transform the file positon using the instance's offset

  public override long Length
  {
    get { return instance.Length - offset ; }
  }

  public override void SetLength( long value )
  {
    instance.SetLength( value + offset );
  }

  public override long Position
  {
    get { return instance.Position - this.offset         ; }
    set {        instance.Position = value + this.offset ; }
  }

  // etc.

  #endregion

  #region override all other methods and properties as simple pass-through calls to the decorated instance.

  public override IAsyncResult BeginRead( byte[] array , int offset , int numBytes , AsyncCallback userCallback , object stateObject )
  {
    return instance.BeginRead( array , offset , numBytes , userCallback , stateObject );
  }

  public override IAsyncResult BeginWrite( byte[] array , int offset , int numBytes , AsyncCallback userCallback , object stateObject )
  {
    return instance.BeginWrite( array , offset , numBytes , userCallback , stateObject );
  }

  // etc.

  #endregion

}

用法非常简单,具体如下:

using ( Stream baseStream = new FileStream( @"c:\foo\bar\somefile.dat" , FileMode.Open , FileAccess.Read , FileShare.Read ) )
{

  // establish your offset
  baseStream.Seek( 100 , SeekOrigin.Begin ) ;

  using ( Stream decoratedStream = OffsetStreamDecorator.Decorate( baseStream ) )
  {
    // now you have a stream that reports a false position and length
    // which you should be able to use anywhere a Stream is accepted.

    PassDecoratedStreamToSomethingExpectingAVanillaStream( decoratedStream ) ;

  }

}

轻松! (所有涉及的样板除外)

相关问题