C#在流上准备40个字节

本文关键字:40个 字节 | 更新日期: 2024-09-22 19:31:30

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

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

我该怎么做?我试着创建自己的流类来连接两个流。。我看过流媒体作家。

当然,这肯定是一种简单的方法。或者另一种方式。我不想把整个文件加载到一个字节数组中,然后把它写回流中。

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

C#在流上准备40个字节

请参阅MergeStream.cs。以下是如何使用它:

var mergeStream = new MergeStream(new MemoryStream(checksum), File.OpenRead(path));
return mergeStream;
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);
        }
    }
}