前言
迩来在做文件存储以及读取的时候,必要用到C#给我们提供的类:File
具体使用方法可以看官方文档:C# File 类
这篇文章只会说File.ReadAllLines和File.ReadAllText的使用以及留意事项
Tips:(肯定要看到末了!!!)
一、File.ReadAllLines
重载使用ReadAllLines(String)打开一个文本文件,读取文件的全部行,然后关闭该文件。ReadAllLines(String, Encoding)打开一个文件,使用指定的编码读取文件的全部行,然后关闭该文件。- public static string[] ReadAllLines (string path);
复制代码 参数
String
要打开以进行读取的文件。
返回
String[]
包含文件全部行的字符串数组。
例子
如今假设我的文件路径是 C:\Users\Admin\Desktop\log.txt
内容如下

文本格式如下
如今我们使用 File.ReadAllLines 读取文件内容,而且打印出来
- string file_path = "C:/Users/Admin/Desktop/log.txt";
- string[] contents = File.ReadAllLines(file_path);
- foreach (string content in contents)
- {
- Debug.Log(content);
- }
复制代码
二、File.ReadAllText
重载使用ReadAllText(String)打开一个文本文件,读取文件的全部行,然后关闭该文件。ReadAllText(String, Encoding)打开一个文件,使用指定的编码读取文件的全部行,然后关闭该文件。- public static string ReadAllText (string path);
复制代码 参数
String
要打开以进行读取的文件。
返回
String
包含文件中全部文本的字符串。
例子
文件路径和内容同上
如今我们使用 File.ReadAllLines 读取文件内容,而且打印出来
- string file_path = "C:/Users/Admin/Desktop/log.txt";
- string content = File.ReadAllText(file_path);
- Debug.Log(content);
复制代码
留意事项
假如在Windows下,我们按下Enter键,也就是我们常说的回车键,实在内部会天生两个字符,一个是 \r(回车符) ,一个是 \n(换行符),假如是计算机专业的大概会熟悉点。
大概出现的标题
我们在编程的时候,大概会使用File.ReadAllText来读取文件,这个时候假如文件有很多换行,那么这个时候比力常见的做法如下
- string file_path = "C:/Users/Admin/Desktop/log.txt";
- string content = File.ReadAllText(file_path);
- string[] contents = content.Split("\n");
- foreach(string s in contents)
- {
- Debug.Log(s);
- }
复制代码 但是如许会有标题,我们来测试下输出什么

看起来挺正常,但是我们继续细化
- foreach (string s in contents)
- {
- Debug.Log("------------");
- Debug.Log("字符串:" + s);
- Debug.Log("字符串长度:" + s.Length);
- }
复制代码 这里我们多打印了一下字符串的长度

我们可以发现,字符串为1,2,3,4,5的,长度却是2
我们得到的contents是颠末Split处置惩罚的,理所应当被分割出来的字符串数组应该是1,2,3,4,5。但为什么对应字符串长度是2,而不是1呢?
实在,假如认真读了上面的留意事项,我们就不能发现,我们如今是在Windows下测试的,我们敲下的Enter键,会天生两个字符,一个是 \r(回车符) ,一个是 \n(换行符)。
windows下换行符是\r\n
\r回车,\n换行
用二进制方式时是\r\n,用文本方式时是\n
当你在记事本或word编辑时,按下enter,该软件默认的方式是插入回车\r,再插入换行\n
以是文本里面表现的是:
但是存储在计算机中(二进制情势)如下
- 1\r\n2\r\n3\r\n4\r\n5\r\n
复制代码 我们可以打印下文件内容
- byte[] bs = File.ReadAllBytes(file_path);
- Debug.Log(bs.Length);
- foreach (byte ch in bs)
- {
- Debug.Log(ch);
- }
复制代码
由于内部是由ASCLL码存储的,以是我们查表,得知13是回车符,也就是\r,10是换行符,也就是\n

为了验证我们的想法,打个断点进去看看

总结
- 只管使用File.ReadAllLines处置惩罚必要换行处置惩罚的文件
- 必要留意Windows下,敲下Enter键是会天生两个字符:\r和\n
来源:https://blog.csdn.net/qq_52855744/article/details/128702422
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |