【问题标题】:c# convert system.IO.Stream to Byte[] [duplicate]c# 将 system.IO.Stream 转换为 Byte[] [重复]
【发布时间】:2012-07-01 05:48:47
【问题描述】:

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

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

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

但在我的情况下,在 paramFile.CopyTo(memoryStream) 行中它什么也没发生,没有例外,应用程序仍然可以工作,但代码不会继续下一行。

谢谢。

【问题讨论】:

  • 啊,对不起,param文件是我在方法中收到的参数,是一个SystemIO.Stream。

标签: c# stream byte


【解决方案1】:

如果您正在读取文件,请使用 File.ReadAllBytes Method:

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

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

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

【讨论】:

  • 真的我有一个流,没有文件。虽然原始数据是一个文件,但我将文件发送到 WCF 中的流中。所以我需要将流转换为字节[]。但是这种方式行不通,因为length属性是long,而read方法使用的是int。
  • 只要不超过 2147483647 (int.MaxValue) 字节,就可以正常工作。否则你必须用计数器组装数组。
【解决方案2】:

这是我为 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;
        }
    }

【讨论】:

  • 雅典,我不认为你有一个额外的 FromByteArray 方法? :-) 我正在使用你的方法,我只需要现在能够将它转换回来。
  • 这可能会有所帮助。 stackoverflow.com/questions/4736155/…
猜你喜欢
  • 2017-12-09
  • 2019-05-15
  • 2011-06-11
  • 2011-10-15
  • 2011-12-24
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 2015-06-04
相关资源
最近更新 更多