我正在寻找一种C#语言的解决方案,它可以将System.IO.Stream转换为byte []。我尝试了下面的代码,但我收到byte []为null。有人可以从下面的代码中指导我所遗漏的内容吗?我从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();
//}
}
答案 0 :(得分: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;
}