• Stream 和 Byte[]互操作


    在.Net的IO操作中经常会用到Stream和Byte[],有两种形式:
    一.Stream->Byte[]:
         1.如果Stream的 Length属性可读,非常的简单,代码如下:

     1  private byte[] GetBytes(Stream stream)
     2        {
     3            if (stream.CanSeek)
     4            {
     5                Byte[] buffer = new byte[stream.Length];
     6                stream.Write(buffer, 0, buffer.Length);
     7                return buffer;
     8            }

     9            //用下面的方法
    10            return null;
    11        }

          2.如果Stream的 Length属性不可读,代码如下:

     1        private byte[] GetBytes(Stream stream)
     2        {
     3            using (MemoryStream mstream = new MemoryStream())
     4            {
     5                byte[] bytes = new byte[1024]; //此处不易设置太大或太小的值,且应该为2的次方
     6                if (stream.CanRead)
     7                {
     8                    while (true)
     9                    {
    10                        int length = stream.Read(bytes, 0, bytes.Length);
    11                        if (length <= 0)
    12                        {
    13                            break;
    14                        }

    15                        mstream.Write(bytes, 0, length);
    16                    }

    17                }

    18                return mstream.ToArray();
    19            }

    20        }

    21
    二.bytes-Stream:
       直接使用内存流即可,代码如下:
    MemoryStream ms=new MemoryStream(bytes)
  • 相关阅读:
    参数_门店
    实现百分比和百分比的累加以及A、B、C类别的标识
    参数范围的选择
    栏目数据合并表达式
    父子维度转化为组
    从参数中获得特定字符串
    多参与多轴
    数据库链接字符串大集合
    闰年2月29天
    sum函数按照类别的值进行取值
  • 原文地址:https://www.cnblogs.com/kokoliu/p/939926.html
Copyright © 2020-2023  润新知