C#将40个字节前置到流上

时间:2013-12-13 10:51:44

标签: c# wcf rest stream prepend

我正在尝试发送文件的FileStream。

但我现在想要在开始时添加40字节的校验和。

我该怎么做?我已经尝试创建自己的流类来连接两个流..而且我看过流编写器。

当然,他们必须是一个简单的方法。或者另一种方式。我不想将整个文件加载到一个字节数组中,并将其写入并将其写回流中。

public Stream getFile(String basePath, String path) {
    return new FileStream(basePath + path, FileMode.Open, FileAccess.Read);
 }

2 个答案:

答案 0 :(得分:3)

MergeStream.cs。以下是您可以使用它的方法:

var mergeStream = new MergeStream(new MemoryStream(checksum), File.OpenRead(path));
return mergeStream;

答案 1 :(得分:0)

byte[] checksum = new byte[40];
//...
FileStream oldFileStream = new FileStream(oldFile, FileMode.Open, FileAccess.Read);
FileStream newFileStream = new FileStream(newFile, FileMode.Create, FileAccess.Write);

using(oldFileStream)
using(newFileStream)
{
    newFileStream.Write(checksum, 0, checksum.Length);
    oldFileStream.CopyTo(newFileStream);
}
File.Copy(newFile, oldFile, overwrite : true);

如果您不想使用临时文件,唯一的解决方案是以ReadWrite模式打开文件并使用两个交替缓冲区:

private static void Swap<T>(ref T obj1, ref T obj2) 
{
    T tmp = obj1;
    obj1 = obj2;
    obj2 = tmp;
}

public static void PrependToFile(string filename, byte[] bytes)
{
    FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite);
    PrependToStream(stream, bytes);
}
public static void PrependToStream(Stream stream, byte[] bytes) 
{
    const int MAX_BUFFER_SIZE = 4096;
    using(stream)
    {
        int bufferSize = Math.Max(MAX_BUFFER_SIZE, bytes.Length);
        byte[] buffer1 = new byte[bufferSize];
        byte[] buffer2 = new byte[bufferSize];
        int readCount1; 
        int readCount2;

        long totalLength = stream.Length + bytes.Length;

        readCount1 = stream.Read(buffer1, 0, bytes.Length);
        stream.Position = 0;
        stream.Write(bytes, 0, bytes.Length);
        int written = bytes.Length;

        while (written < totalLength)
        {
            readCount2 = stream.Read(buffer2, 0, buffer2.Length);
            stream.Position -= readCount2;
            stream.Write(buffer1, 0, readCount1);

            written += readCount1;

            Swap(ref buffer1, ref buffer2);
            Swap(ref readCount1, ref readCount2);
        }
    }
}