用C#讀取txt文件的方法
1、使用FileStream讀寫文件
?
文件頭:
?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
?
讀文件核心代碼:
?
byte[] byData = new byte[100];
char[] charData = new char[1000];
?
try
{
FileStream sFile = new FileStream("文件路徑",FileMode.Open);
sFile.Seek(55, SeekOrigin.Begin);
sFile.Read(byData, 0, 100); //第一個參數是被傳進來的字節數組,用以接受FileStream對象中的數據,第2個參數是字節數組中開始寫入數據的位置,它通常是0,表示從數組的開端文件中向數組寫數據,最后一個參數規定從文件讀多少字符.
}
catch (IOException e)
{
Console.WriteLine("An IO exception has been thrown!");
Console.WriteLine(e.ToString());
Console.ReadLine();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
Console.ReadLine();
?
寫文件核心代碼:
?
FileStream fs = new FileStream(文件路徑,FileMode.Create);
//獲得字節數組
byte [] data =new UTF8Encoding().GetBytes(String);
//開始寫入
fs.Write(data,0,data.Length);
//清空緩沖區、關閉流
fs.Flush();
fs.Close();
?
2、使用StreamReader和StreamWriter
?
文件頭:
?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
?
StreamReader讀取文件:
?
StreamReader objReader = new StreamReader(文件路徑);
????? string sLine="";
????? ArrayList LineList = new ArrayList();??
????? while (sLine != null)
????? {
??????? sLine = objReader.ReadLine();
??????? if (sLine != null&&!sLine.Equals(""))
????????? LineList.Add(sLine);
????? }
??????????? objReader.Close();
??????????? return LineList;
?
StreamWriter寫文件:
?
? FileStream fs = new FileStream(文件路徑, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write(String);
?//清空緩沖區
sw.Flush();
//關閉流
sw.Close();
fs.Close();
用C#讀取.txt文件,常用
StreamReader sr = new StreamReader("TestFile.txt")///StreamReader sr = new StreamReader("TestFile.txt",Encoding.GetEncoding("GB2312"))
///GBK
String line;
while ((line = sr.ReadLine()) != null)
{
?? textBox1 .Text +=ii.ToString ()+" -"+line.ToString()+"\r\n";
}
加入引用:System.IO
StreamReader objReader = new StreamReader("c:\\test.txt");
???? System.IO 命名空間中的對象,尤其是 System.IO.StreamReader 類。
\r\n一般一起用,用來表示鍵盤上的回車鍵.也可只用\n.\t表示鍵盤上的“TAB”鍵。