Din*_*esh 1 c# byte alfresco filestream
我正在寻找一种可以将 System.IO.Stream 转换为 byte[] 的 C# 语言解决方案。我已经尝试了下面的代码,但我收到的字节 [] 为空。有人可以指导我从下面的代码中缺少什么吗?我从 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();
//}
}
Run Code Online (Sandbox Code Playgroud)
一旦我为它做了一个扩展方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10218 次 |
| 最近记录: |