代码之家  ›  专栏  ›  技术社区  ›  Greg

在C中将流转换为文件流#

  •  13
  • Greg  · 技术社区  · 14 年前

    使用c_将流转换为文件流的最佳方法是什么?

    我正在处理的函数有一个包含上载数据的流传递给它,我需要能够执行stream.read()、stream.seek()方法,这些方法是filestream类型的方法。

    一个简单的演员阵容不起作用,所以我在这里寻求帮助。

    1 回复  |  直到 8 年前
        1
  •  20
  •   Jon Skeet    14 年前

    Read Seek 方法是否在 Stream 类型,而不仅仅是 FileStream . 只是不是所有的流都支持它们。(我个人更喜欢使用 Position property 过度调用 寻找 但归根结底还是一样的。)

    如果您希望将数据存储在内存中而不是将其转储到文件中,为什么不直接将其读取到 MemoryStream ?这支持寻找。例如:

    public static MemoryStream CopyToMemory(Stream input)
    {
        // It won't matter if we throw an exception during this method;
        // we don't *really* need to dispose of the MemoryStream, and the
        // caller should dispose of the input stream
        MemoryStream ret = new MemoryStream();
    
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ret.Write(buffer, 0, bytesRead);
        }
        // Rewind ready for reading (typical scenario)
        ret.Position = 0;
        return ret;
    }
    

    用途:

    using (Stream input = ...)
    {
        using (Stream memory = CopyToMemory(input))
        {
            // Seek around in memory to your heart's content
        }
    }
    

    这与使用 Stream.CopyTo .NET 4中引入的方法。

    如果你 事实上 要写入文件系统,可以执行类似的操作,首先写入文件,然后倒流…但是之后您需要注意删除它,以避免在磁盘上乱丢文件。