如何将MemoryStream数据写入文件

Rad*_*lav 0 .net streaming c#-4.0

我有这个代码:

private void SaveStreamToFile(string fileFullPath, Stream stream)
    {
        if (stream.Length == 0) return;

        // Create a FileStream object to write a stream to a file
        using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
        {
            // Fill the bytes[] array with the stream data
            byte[] bytesInStream = new byte[stream.Length];
            stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

            // Use FileStream object to write to the specified file
            fileStream.Write(bytesInStream, 0, bytesInStream.Length);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我把这个方法叫做SaveStreamToFile(@"f:\ Test.txt",memoryStream);

我收到错误:不允许文件操作.访问路径'f:\ Test.txt'被拒绝.

Jon*_*eet 8

好吧,大概这意味着你没有写访问权限f:\Test.txt.这确实是.NET范围之外的问题.

但是,您的方法已被破坏.这里:

byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
Run Code Online (Sandbox Code Playgroud)

假设你可以得到的数据流(不是所有的流支持此)的长度,而你也假设Read将读取整个事情一气呵成.情况不一定如此.

如果您使用的是.NET 4,则可以使用Stream.CopyTo,这将使生活变得更加简单.(虽然如果流中没有数据,这将无法帮助您中止.)但是您仍然需要修复无法写入的问题f:\Test.txt.