string与byte[](UTF-8)

//string to byte[]
string str = "abc中文";
//0x61 0x62 0x63 0xE4 0xB8 0xAD 0xE6 0x96 0x87
byte[] bytes = Encoding.UTF8.GetBytes(str); //byte[] to string
//abc中文
str = Encoding.UTF8.GetString(bytes);

string与byte[](ASCII)

//string to byte[]
string str = "abc中文";
//注意:由于ASCII不支持中文,中文转码失败会变成问号(0x3F)
//0x61 0x62 0x63 0x3F 0x3F
byte[] bytes = Encoding.ASCII.GetBytes(str); //byte[] to string
//abc??
str = Encoding.ASCII.GetString(bytes);
Console.WriteLine(str);

string与byte[](GBK)

GBK是GB2312的扩展,其实现在所使用的GB码都是GBK编码,GB2312早就是过去时,但GB2312这个名字由于用了太久,惯性太大,所以一直保留着,并在在当今GB2312与GBK这两个名称被看作是等价的。在dotnet core中,GBK编码默认不被支持,必须引入nuget包:System.Text.Encoding.CodePages,且在程序入口处注册:Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

//string to byte[]
string str = "abc中文";
//0x61 0x62 0x63 0xD6 0xD0 0xCE 0xC4
byte[] bytes = Encoding.GetEncoding("GBK").GetBytes(str); //byte[] to string
//abc中文
str = Encoding.GetEncoding("GBK").GetString(bytes);

byte[]与MemoryStream

Stream其实就是对byte[]的一种抽象与封装,计算机世界里的一切代码数据,其实都可以看做Stream,里面包含的是一个个有次序的字节。当然了,跟byte[]相比,Stream通常不能随机访问。MemoryStream表示内存中的Stream,数据存在于内存中,所以它是一个能随机访问的Stream。byte[]与MemoryStream之间能非常方便地转换。

//byte[] to MemoryStream
byte[] bytes = {0x61, 0x62, 0x63, 0xE4, 0xB8, 0xAD, 0xE6, 0x96, 0x87};
MemoryStream ms = new MemoryStream(bytes); //MemoryStream to byte[]
bytes = ms.ToArray();

string与MemoryStream

string与byte[]互转,byte[]与MemoryStream互转,所以这个就不是问题了。

byte[]与Stream

不是所有Stream都像MemoryStream一样能直接和byte[]互转,比如说FileStream,那怎么办呢?不能直接转,那就使用“读写”这两个动作啊,写到Stream去,以及从Stream中读取。

//byte[] to Stream
byte[] bytes = {0x61, 0x62, 0x63, 0xE4, 0xB8, 0xAD, 0xE6, 0x96, 0x87};
using (FileStream fs = File.Create("d:\\test.txt")) {
fs.Write(bytes);
} //Stream to byte[]
using (FileStream fs = File.OpenRead("d:\\test.txt")) {
bytes = new byte[fs.Length];
fs.Read(bytes);
Console.WriteLine(BytesToHexString(bytes));
}

string与文件

由于我们经常要读取文本文件,或把文本写到文件中去,所以dotnet提供了两个简便方法,让我们可以不管FileStream。

string str = "ABC中文";

//string to file
File.WriteAllText("d:\\test.txt", str); //file to string
str = File.ReadAllText("d:\\test.txt");

注意,这两个方法都是认为文件使用了UTF-8编码。另外我是推荐使用这两个方法快速访问文本文件的,因为不同编码格式的文本文件其实还有个字节序标记(BOM,Byte Order Mark)的概念,不过这里就不展开了。

string与Stream

如果Stream来自于网络,没有File.ReadAllText这种方法,那应该怎么做?你当然可以用Stream的Read/Write方法,但读出来byte[]之后还需要再转为string,有点周折。所以dotnet引入了两个对象,StreamReader和StreamWriter,用它们可以实现string到Stream之间的转换。(为简单起见,下面的例子依然使用FileStream)

//Write string to Stream
using (FileStream fs = File.Create("d:\\test.txt")) {
StreamWriter writer = new StreamWriter(fs);
writer.Write("ABC中文");
writer.Flush();
} //Read string from Stream
using (FileStream fs = File.OpenRead("d:\\test.txt")) {
StreamReader reader = new StreamReader(fs)
string str = reader.ReadToEnd();//也可以用ReadLine逐行读取
}

注意1:writer自带缓存调用Flush方法确保数据已经写入流中,另一种方法是将writer包到using代码块中,例子见下
注意2:StreamWriter和StreamReader默认使用UTF-8编码,如果要换一种编码方式,需要手动指定,例子见下

//Write string to Stream
using (FileStream fs = File.Create("d:\\test.txt")) {
using (StreamWriter writer = new StreamWriter(fs, Encoding.GetEncoding("GBK"))) {
writer.Write("ABC中文");
}
}
//Read string from Stream
using (FileStream fs = File.OpenRead("d:\\test.txt")) {
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GBK"));
string str = reader.ReadToEnd();//也可以用ReadLine逐行读取
}

注意:要使用GBK编码,请参考“string与byte[](GBK)”中的描述。

dotnet中Stream、string及byte[]的相关操作的更多相关文章

  1. (转)Go中的string和[]byte对比

    本文转自:https://sheepbao.github.io/post/golang_byte_slice_and_string/ 作者:boya 声明:本文目的仅仅作为个人mark,所以在翻译的过 ...

  2. C#中有关string和byte[]转换的问题

    byte[] byteArray = System.Text.Encoding.Default.GetBytes( str ); 怎么样,够简单吧? 反过来也是一样,把byte[]转成string: ...

  3. WebView中的视频全屏的相关操作

    近期工作中,基本一直在用WebView,今天就把它整理下: WebView 顾名思义,就是放一个网页,一个看起来十分简单,可是用起来不是那么简单的控件. 首先你肯定要定义,初始化一个webview,事 ...

  4. golang中文件以及文件夹路径相关操作

    获取目录中所有文件使用包: io/ioutil 使用方法: ioutil.ReadDir 读取目录 dirmane 中的所有目录和文件(不包括子目录) 返回读取到的文件的信息列表和读取过程中遇到的任何 ...

  5. C#中执行批处理文件(.bat),执行数据库相关操作

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  6. java 中的try catch在文件相关操作的使用

    import java.io.CharConversionException; import java.io.FileNotFoundException; import java.io.FileRea ...

  7. 浅谈python中文件和文件夹的相关操作

    文件操作 文件的打开与关闭 打开文件 使用open(文件名,访问方式)函数,可以打开一个已存在的文件,或者创建一个新的文件. 示例如下: f = open('test.txt') # 访问方式可以省略 ...

  8. 在Javascript中使用String.startsWith和endsWith

    在Javascript中使用String.startsWith和endsWith 在操作字符串(String)类型的时候,startsWith(anotherString)和endsWith(anot ...

  9. redis对sorted_set进行的相关操作

    redis对sorted_set(有序集合)类型操作的相关命令以及如何在python使用这些命令 redis对sorted_set(有序集合)类型操作的命令: 命令 语法 概述 返回值 Redis Z ...

随机推荐

  1. SSM-MyBatis-11:Mybatis中查询全部用resultmap

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 实体类很普通,四个字段,编号,名字,作者名,价格 在接口中的方法声明如下 //查全部 public List& ...

  2. 【阿里聚安全·安全周刊】Python库现后门 可窃取用户SSH信息|Facebook再曝300万用户数据泄露

    本周七个关键词:Python库现后门丨Facebook再曝数据泄露丨加密协议被曝严重漏洞丨英国报摊将出售"色情通行证"丨HTTPS的绿色锁图标丨机器学习和预测应用的API丨Ecli ...

  3. Windows Defender Service 是选择Windows 10系统的最大障碍!

    今天从早上开始,Windows Defender Service服务从CPU消耗资源30%一直上升到60%并且无法下降. 我一直使用的是Windows 10 Enterprise 2016长期服务支持 ...

  4. Scrapy 1.4 文档 05 命令行工具

    在系统命令行中,使用 scrapy 命令可以创建工程或启动爬虫,它控制着 Scrapy 的行为,我们称之为 Scrapy 命令行工具(command-line tool)或 Scrapy 工具(Scr ...

  5. Project facet Java version 1.8 not supported JDK版本不对无法启动项目解决办法

    https://jingyan.baidu.com/article/6c67b1d69a59a02787bb1e30.html

  6. 关于maven的配置使用 这一篇还比较全 2017.12.13

    https://www.cnblogs.com/tangshengwei/p/6341462.html

  7. 7-20 jquery遍历节点,bootstrap模态框绑定事件和解绑,mock.js,model.urlroot,id,打基础

    7-19 1:$(event.target).parents().filter("tr").find("host-name") 为什么选择不到别的host-na ...

  8. 使用jekyll和Github搭建个人博客

    一.使用jekyll和Github三步搭建个人博客 在 Github 上建一个库,库的名字是xxx.github.com,其中的xxx是你的github的账号名(图中标注的不要勾选) 注:如果没有Gi ...

  9. python类型转换convert实例分析

    在python的开发过程中,难免会遇到类型转换,这里给出常见的类型转换demo: 类型 说明 int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 ...

  10. [python]pip总结

    基本命令解释 安装 pip 下载 地址 https://pypi.python.org/pypi/pip 下载 tar.gz 打开cmd,把路径切换到解压后的文件夹 python -m python ...