1.添加命名空間
System.IO;
System.Text;
2.文件的讀取
(1).使用FileStream類進行文件的讀取,并將它轉換成char數組,然后輸出。
byte[] byData = new byte[100];
char[] charData = new char[1000];
public void Read()
{
try
{
FileStream file = new FileStream("E://test.txt", FileMode.Open);
file.Seek(0, SeekOrigin.Begin);
file.Read(byData, 0, 100); //byData傳進來的字節數組,用以接受FileStream對象中的數據,第2個參數是字節數組中開始寫入數據的位置,它通常是0,表示從數組的開端文件中向數組寫數據,最后一個參數規定從文件讀多少字符.
Decoder d = Encoding.Default.GetDecoder();
d.GetChars(byData, 0, byData.Length, charData, 0);
Console.WriteLine(charData);
file.Close();
}
catch (IOException e)
{
Console.WriteLine(e.ToString());
}
}
(2).使用StreamReader讀取文件,然后一行一行的輸出。
public void Read(string path)
{
StreamReader sr = new StreamReader(path,Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line.ToString());
}
}
3.文件的寫入
(1).使用FileStream類創建文件,然后將數據寫入到文件里。
public void Write()
{
FileStream fs = new FileStream("E://ak.txt", FileMode.Create);
//獲得字節數組
byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
//開始寫入
fs.Write(data, 0, data.Length);
//清空緩沖區、關閉流
fs.Flush();
fs.Close();
}
(2).使用FileStream類創建文件,使用StreamWriter類,將數據寫入到文件。
public void Write(string path)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write("Hello World!!!!");
//清空緩沖區
sw.Flush();
//關閉流
sw.Close();
fs.Close();
}