zoukankan      html  css  js  c++  java
  • Stream 和 Byte[] 互操作

    在 .Net 的 IO 操作中经常会用到 Stream 和 Byte[],有两种形式:

    一、Stream -> Byte[]:

    1. 如果 Stream 的 Length 属性可读,非常的简单,代码如下:

    private byte[] GetBytes(Stream stream)
    {
        if (stream.CanSeek)
        {
            Byte[] buffer = new byte[stream.Length];
            stream.Write(buffer, 0, buffer.Length);
            return buffer;
        }
        //用下面的方法
        return null;
    }

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

    private byte[] GetBytes(Stream stream)
    {
        using (MemoryStream mstream = new MemoryStream())
        {
            byte[] bytes = new byte[1024]; //此处不易设置太大或太小的值,且应该为2的次方
            if (stream.CanRead)
            {
                while (true)
                {
                    int length = stream.Read(bytes, 0, bytes.Length);
                    if (length <= 0)
                    {
                        break;
                    }
                    mstream.Write(bytes, 0, length);
                }
            }
            return mstream.ToArray();
        }
    }

    二、bytes -> Stream:

    直接使用内存流即可 , 代码如下:

    MemoryStream ms=new MemoryStream(bytes)

     字符串(string)与 byte(byte[]) 之间的转换。

    byte[] buffer = System.Text.Encoding.Default.GetBytes("字符串");
    string str = System.Text.Encoding.Default.GetString(buffer);
  • 相关阅读:
    MySql模糊查询like通配符使用详细介绍
    使用powershell批量添加Qt的文件(生成pro)
    宏定义的教训
    使用powershell批量添加Keil和IAR的头文件路径
    python和数据科学(Anaconda)
    CDCE913产生任意频率
    QT中检索设定目录下所有指定文件的方法
    QT中将ASCII转换为对应数值的方法
    STM8如何使用自带的bootloader
    QT中使用函数指针
  • 原文地址:https://www.cnblogs.com/jordan2009/p/2728864.html
Copyright © 2011-2022 走看看