如何从非零位置开始从 Memorystream 写入 FileStream?

How can I write to a FileStream from a Memorystream starting from a non-zero position?

我需要从 Memorystream 写入简单的 Filestream。问题是我的内存流包含文件名及其字节序列,用“|”分隔。所以它是这样的:name.extension|BYTES。我现在用来写的代码是:

Dim j As Integer = 1
    Dim name As String
    name = ""
    ms.Read(temp, 0, 1)
    Do While (UTF8.GetString(temp, 0, 1) <> "|")
        name += UTF8.GetString(temp, 0, 1)
        j += 1
        ms.Read(temp, 0, 1)
    Loop

这就是我获取文件名的方式,并且:

Dim fs As FileStream = File.Create(sf.FileName()) 'SaveFileDialog
        ms.Seek(j, SeekOrigin.Begin) 'starting to write after "|" char

        Do
            ms.Read(temp, 0, 1)
            fs.Write(temp, 0, 1)
            j += 1
        Loop While ms.Length - j <> 0 'YES... byte after byte

        fs.Close()
        fs.Dispose()
        ms.close()
        ms.Dispose()

我是这样写文件的。我知道可能有些东西可以写得更好,但这就是我请求你帮助的原因。我尝试使用 MememoryStream.WriteTo(FileStream) 但它也从文件名开始写入。代码可以改进吗?非常感谢!

看了Mark的建议后,我觉得他的方法好多了。 Streams 旨在相互连接,因此不要手动执行框架的任务。这是一个有效的测试。

using (var ms = new MemoryStream())
{
    //Prepare test data.
    var text = "aFileName.txt|the content";
    var bytes = Encoding.UTF8.GetBytes(text);
    ms.Write(bytes, 0, bytes.Length);
    //Seek back to origin to simulate a fresh stream
    ms.Seek(0, SeekOrigin.Begin);

    //Read until you've consumed the | or you run out of stream.
    var oneByte = 0;
    while (oneByte >= 0 && Convert.ToChar(oneByte) != '|')
    {
        oneByte = ms.ReadByte();
    }

    //At this point you've consumed the filename and the pipe.
    //Your memory stream is now at the proper position and you
    //can simply tell it to dump its content into the filestream.
    using (var fs = new FileStream("test.txt", FileMode.Create))
    {
        ms.CopyTo(fs);
    }
}

请注意,流是一次性对象。您应该使用 'using' 构造而不是关闭和处置,因为即使抛出异常,它也会为您处理。