c# 将 system.IO.Stream 转换为 Byte[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11266141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:11:27  来源:igfitidea点击:

c# convert system.IO.Stream to Byte[]

c#streambyte

提问by álvaro García

I would like to know how to convert a stream to a byte.

我想知道如何将流转换为字节。

I find this code, but in my case it does not work:

我找到了这段代码,但在我的情况下它不起作用:

var memoryStream = new MemoryStream();
paramFile.CopyTo(memoryStream);
byte[] myBynary = memoryStream.ToArray();
myBinary = memoryStream.ToArray();

But in my case, in the line paramFile.CopyTo(memoryStream) it happens nothing, no exception, the application still works, but the code not continue with the next line.

但就我而言,在 paramFile.CopyTo(memoryStream) 行中,它什么也没发生,无一例外,应用程序仍然有效,但代码不会继续下一行。

Thanks.

谢谢。

采纳答案by JamieSee

If you are reading a file just use the File.ReadAllBytes Method:

如果您正在读取文件,只需使用File.ReadAllBytes 方法

byte[] myBinary = File.ReadAllBytes(@"C:\MyDir\MyFile.bin");

Also, there is no need to CopyTo a MemoryStream just to get a byte array as long as your sourceStream supports the Length property:

此外,只要您的 sourceStream 支持 Length 属性,就不需要 CopyTo a MemoryStream 来获取字节数组:

byte[] myBinary = new byte[paramFile.Length];
paramFile.Read(myBinary, 0, (int)paramFile.Length);

回答by Athens Holloway

This is an extension method i wrote for the Stream class

这是我为 Stream 类编写的扩展方法

 public static class StreamExtensions
    {
        public static byte[] ToByteArray(this Stream stream)
        {
            stream.Position = 0;
            byte[] buffer = new byte[stream.Length];
            for (int totalBytesCopied = 0; totalBytesCopied < stream.Length; )
                totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
            return buffer;
        }
    }