【问题标题】:Writing and reading streams with offset to reduce disc seeks使用偏移量写入和读取流以减少磁盘寻道
【发布时间】:2014-03-16 18:42:43
【问题描述】:

我正在读取一个文件并将该文件的流写入一个文件,我想要做的是在一个文件中写入多个文件并通过它们的偏移量读取它们。

在写入文件时,我知道我需要知道文件偏移量和流的长度才能读回文件。

var file = @"d:\foo.pdf";

var stream = File.ReadAllBytes(file);
// here i have the length of the 
Console.WriteLine(stream.LongLength);

using (var br = new BinaryWriter(File.Open(@"d:\foo.bin", FileMode.OpenOrCreate)))
{
     br.Write(stream);
}

我需要在写入多个文件时找到偏移量。

另外,在回读文件时,我如何从偏移量开始并向前读取长度?

最后,这种方法会减少磁盘寻道次数吗?

【问题讨论】:

    标签: c# file io stream


    【解决方案1】:

    要读回各种片段,您需要存储各个文件的长度。例如:

    using(var dest = File.Open(@"d:\foo.bin", FileMode.OpenOrCreate))
    {
        Append(dest, file);
        Append(dest, anotherFile);
    }
    ...
    static void AppendFile(Stream dest, string path)
    {
        using(var source = File.OpenRead(path))
        {
            var lenHeader = BitConverter.GetBytes(source.Length);
            dest.Write(lenHeader, 0, 4);
            source.CopyTo(dest);
        }
    }
    

    然后要回读,您可以执行以下操作:

    using(var source = File.OpenRead(...))
    {
        int len = ReadLength(source);
        stream.Seek(len, SeekOrigin.Current); // skip the first file
        len = ReadLength(source);
        // TODO: now read len-many bytes from the second file        
    }
    static int ReadLength(Stream stream)
    {
        byte[] buffer = new byte[4];
        int count = 4, offset = 0, read;
        while(count != 0 && (read = stream.Read(buffer, offset, count)) > 0)
        {
            count -= read;
            offset += read;
        }
        if (count != 0) throw new EndOfStreamException();
        return BitConverter.ToInt32(buffer, 0);
    }
    

    关于读取 len-many 字节;您可以在阅读时跟踪它并减少它,或者您可以创建一个长度有限的Stream 包装器。两者都可以。

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 2012-03-02
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多