
它们都一次将文本内容全部读完,并返回一个包含全部文本内容的字符串
string str = File.ReadAllText(@"c:\temp\ascii.txt")
// 也可以指定编码方式
string str2 = File.ReadAllText(@"c:\temp\ascii.txt", Encoding.ASCII)
也可以使用方法File.ReadAllLines。该方法返回一个字符串数组。每一行都是一个数组元素。
string[] strs = File.ReadAllLines(@"c:\temp\ascii.txt")
// 也可以指定编码方式
string[] strs2 = File.ReadAllLines(@"c:\temp\ascii.txt", Encoding.ASCII)
当文本的内容比较大时,我们就不要将文本内容一次读完,而应该采用流(Stream)的方式来读取内容。.Net为我们封装了StreamReader类。初始化StreamReader类有很多种方式。下面我罗列出几种
StreamReader sr1 = new StreamReader(@"c:\temp\utf-8.txt")
// 同样也可以指定编码方式
StreamReader sr2 = new StreamReader(@"c:\temp\utf-8.txt", Encoding.UTF8)
FileStream fs = new FileStream(@"C:\temp\utf-8.txt", FileMode.Open, FileAccess.Read, FileShare.None)
StreamReader sr3 = new StreamReader(fs)
StreamReader sr4 = new StreamReader(fs, Encoding.UTF8)
FileInfo myFile = new FileInfo(@"C:\temp\utf-8.txt")
// OpenText 创建一个UTF-8 编码的StreamReader对象
StreamReader sr5 = myFile.OpenText()
// OpenText 创建一个UTF-8 编码的StreamReader对象
StreamReader sr6 = File.OpenText(@"C:\temp\utf-8.txt")
初始化完成之后,你可以每次读一行,也可以每次读一个字符 ,还可以每次读几个字符,甚至也可以一次将所有内容读完。
// 读一行
string nextLine = sr.ReadLine()
// 读一个字符
int nextChar = sr.Read()
// 读100个字符
int nChars = 100
char[] charArray = new char[nChars]
int nCharsRead = sr.Read(charArray, 0, nChars)
// 全部读完
string restOfStream = sr.ReadToEnd()
使用完StreamReader之后,不要忘记关闭它: sr.Closee()
假如我们需要一行一行的读,将整个文本文件读完,下面看一个完整的例子:
StreamReader sr = File.OpenText(@"C:\temp\ascii.txt")
string nextLine
while ((nextLine = sr.ReadLine()) != null)
{
安装驱动程序,插上ic卡读写器即可使用读写器自带的测试程序。要是软件有集成相应型号的读写器,只读把读写器插上电脑即可使用。要是软件没有集成的话,也可以采用即插即用的ic卡读写器。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)