string与byte[]相互转换方法

本文提供了两个实用的方法:将字节数组转换为字符串,以及将字符串转换为字节数组。这两种转换常用于文件操作、网络传输等场景,尤其是在处理UTF-8编码的数据时。文章详细展示了如何用C#实现这些转换,并通过代码示例解释了其工作原理。

  1.         public static string ByteArray2String(byte[] contentByte)
  2.         {
  3.             string result = string.Empty;
  4.             if(contentByte != null)
  5.                 result = Encoding.GetEncoding("UTF-8").GetString(contentByte, 0, contentByte.Length);

  6.             return result;
  7.         }


  8.         public static byte[] String2ByteArray(string documentText)//(Editor myEditor)
  9.         {
  10.             byte[] contentBytes = null;

  11.             /*!!! myEditor.Html中的IMAGE是路径,BodyHtml中的是转换后byte[],但bodyhtml只包含body内的html,
  12.              取整个文件的html需要使用DocumentText */
  13.             if (string.IsNullOrWhiteSpace(documentText))
  14.                 contentBytes = null;
  15.             else
  16.                 contentBytes = Encoding.GetEncoding("UTF-8").GetBytes(documentText);

  17.             return contentBytes;
  18.         }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值