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

时间:2016-12-21 19:53:48

标签: vb.net filestream memorystream

我需要从Memorystream写入简单的文件流。问题是我的memorystream保存文件名及其用“|”分隔的字节序列。所以它是这样的: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),但它也开始从文件名写入。代码可以改进吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

在阅读马克的建议后,我认为他的方法要好得多。 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'构造来代替关闭和处理,因为即使抛出异常,它也会为您处理它。