Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何将MemoryStream数据写入文件_.net_C# 4.0_Streaming - Fatal编程技术网

.net 如何将MemoryStream数据写入文件

.net 如何将MemoryStream数据写入文件,.net,c#-4.0,streaming,.net,C# 4.0,Streaming,我有以下代码: 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(fi

我有以下代码:

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);
        }
    }
我像这样调用这个方法SaveStreamToFile(@“f:\Test.txt”,memoryStream)


我得到错误:文件操作不允许。对路径“f:\Test.txt”的访问被拒绝。

好吧,这可能意味着您没有对
f:\Test.txt的写访问权。这是一个超出.NET范围的问题,真的

然而,你的方法被破坏了。在这里:

byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
您假设您可以获得流的长度(并非所有流都支持此功能),并且您还假设
Read
将一次性读取整个内容。情况未必如此


如果您使用的是.NET4,那么您可以使用它,这将使生活更加简单。(虽然这不会帮助您在流中没有数据时中止。)但您仍然需要解决无法写入
f:\Test.txt
的问题。

我也遇到了这个错误,正如Jon Skeet所建议的,第一个问题是访问权限


这是因为我没有使用相对路径到达目标文件夹。一旦我更改了它,我就可以轻松地访问和修改。

您不必从流中提取字节,使用
stream.CopyTo(fileStream)