当前位置:网站首页>C#读取本地文件夹中所有文件文本内容的方法
C#读取本地文件夹中所有文件文本内容的方法
2022-07-26 16:10:00 【汤圆一碗】
- 了解测试了下C#读取本地txt文本内容的方法,在Unity中测试读取本地文件,txt文本编码格式为ANSI的时候,中文输出为乱码;txt文本编码格式为unicode、unicode big endian、utf-8的时候,中文能正常输出。
下面为两种读取txt文本内容的方法:(记得引用using System.IO)
string path = "C:\\Users\\hahaha\\Desktop\\test";
//方法一
DirectoryInfo directoryInfo = new DirectoryInfo(path);
FileInfo[] files = directoryInfo.GetFiles();
for (int i = 0; i < files.Length; i++)
{
if(files[i].Extension.Equals(".txt")) //判断是否为txt文件
{
string[] strs = File.ReadAllLines(path + "\\" + files[i].Name); //文本文件完整路径
for (int j = 0; j < strs.Length; j++)
{
Debug.Log("$$$$$$" + strs[j].ToString());
}
}
}
//方法二
string[] strPath = Directory.GetFiles(path, "*.txt"); //只读取txt文件,得到的是一个包含所有txt文件路径的字符数组
foreach(string p in strPath)
{
string[] strs3 = File.ReadAllLines(p); //内容分行读取
for (int j = 0; j < strs3.Length; j++)
{
Debug.Log("&&&&&&" + strs3[j].ToString());
}
string ss = File.ReadAllText(p); //内容全部读取
Debug.Log("%%%" + ss);
foreach(var line in File.ReadLines(p)) //内容分行迭代读取
{
Debug.Log("@@@@" + line.ToString());
}
}
- 在方法二中比较了File的三种读取方法的差异:
(1)ReadAllLines和ReadAllText的区别:
File.ReadAllLines()返回一个字符串数组。每个字符串包含文件的一行。
File.ReadAllText()返回一个包含文件所有行的单个字符串。
(2)ReadAllLines和ReadLines的区别
File.ReadAllLines()方法一次读取整个文件并返回字符串[]数组,因此在使用大型文件时需要花费时间,不推荐用户等待,直到返回整个数组.
File.ReadLines()返回一个IEnumerable< string>并且它一次不读取整个文件,所以当使用大尺寸文件时,这是一个更好的选择.
边栏推荐
猜你喜欢
Specific practice cases of "card note taking method" in Siyuan

Pandora IOT development board learning (RT thread) - Experiment 17 esp8266 experiment (learning notes)

FTP protocol

vlang捣鼓之路

Linux Installation mysql8.0.29 detailed tutorial

数字化转型怎么就那么的难?!

2022年最新西藏建筑施工架子工(建筑特种作业)模拟考试试题及答案

What is the complexity often said during the interview?

Mapwithstate of spark streaming state flow

Some cutting-edge research work sharing of SAP ABAP NetWeaver containerization
随机推荐
13 years of senior developers share a year of learning rust experience: from the necessary bibliography to code practice
Question collection come and ask nllb authors! (Zhiyuan live issue 24)
微信小程序---网络数据请求
Operating system migration practice: deploying MySQL database on openeuler
Re7: reading papers fla/mlac learning to predict charges for critical cases with legal basis
Interface test for quick start of JMeter
Implementation of personalized healthy diet recommendation system based on SSM
vscode批量删除
Understanding weight sharing in convolutional neural networks
阿里云DMS MySQL云数据库建表报错,求解!!
Comprehensive design of an oppe homepage -- Design of navigation bar
【物理模拟】最简单的shape matching的原理与实践
Bugku login1
辨析 Ruby 中的 Method 与 Proc
Pat grade a 1046 shortest distance
ACL-IJCAI-SIGIR顶级会议论文报告会(AIS 2022)笔记3:对话和生成
Technology vane | interpretation of cloud native technology architecture maturity model
PAT甲级1048 Find Coins
RE9: read the paper deal inductive link prediction for nodes having only attribute information
Some cutting-edge research work sharing of SAP ABAP NetWeaver containerization