【问题标题】:Converting System.IO.Stream to Byte[] [duplicate]将 System.IO.Stream 转换为 Byte[] [重复]
【发布时间】:2017-12-09 06:39:08
【问题描述】:

我正在寻找可以将 System.IO.Stream 转换为 byte[] 的 C# 语言解决方案。我已经尝试了下面的代码,但我收到的 byte[] 为空。有人可以指导我从下面的代码中缺少什么吗?我从 Alfresco Web 服务接收,除非保存到临时位置,否则我无法读取文件。

 private static byte[] ReadFile(Stream fileStream)
    {
        byte[] bytes = new byte[fileStream.Length];

        fileStream.Read(bytes, 0, Convert.ToInt32(fileStream.Length));
        fileStream.Close();

        return bytes;

        //using (MemoryStream ms = new MemoryStream())
        //{
        //    int read;
        //    while ((read = fileStream.Read(bytes, 0, bytes.Length)) > 0)
        //    {
        //        fileStream.CopyTo(ms);
        //    }
        //    return ms.ToArray();
        //}
    }

【问题讨论】:

标签: c# byte alfresco filestream


【解决方案1】:

一旦我为它做了一个扩展方法:

public static byte[] ToArray(this Stream s)
{
    if (s == null)
        throw new ArgumentNullException(nameof(s));
    if (!s.CanRead)
        throw new ArgumentException("Stream cannot be read");

    MemoryStream ms = s as MemoryStream;
    if (ms != null)
        return ms.ToArray();

    long pos = s.CanSeek ? s.Position : 0L;
    if (pos != 0L)
        s.Seek(0, SeekOrigin.Begin);

    byte[] result = new byte[s.Length];
    s.Read(result, 0, result.Length);
    if (s.CanSeek)
        s.Seek(pos, SeekOrigin.Begin);
    return result;
}

【讨论】:

  • 请注意,即使查询 .Position 也可能会失败 - 并非所有流都支持这一点
  • 好点,已修复。顺便说一句,我也需要修复我的库。 :)
猜你喜欢
  • 2012-07-01
  • 2019-05-15
  • 2011-10-15
  • 2011-12-24
  • 2011-06-11
  • 2015-06-04
  • 2011-06-08
  • 2011-05-18
相关资源
最近更新 更多