C#讀寫txt文件多種方法實例代碼
1.添加命名空間
System.IO;
System.Text;
2.文件的讀取
(1).使用FileStream類進行文件的讀取,并將它轉換成char數(shù)組,然后輸出。
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傳進來的字節(jié)數(shù)組,用以接受FileStream對象中的數(shù)據(jù),第2個參數(shù)是字節(jié)數(shù)組中開始寫入數(shù)據(jù)的位置,它通常是0,表示從數(shù)組的開端文件中向數(shù)組寫數(shù)據(jù),最后一個參數(shù)規(guī)定從文件讀多少字符.
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類創(chuàng)建文件,然后將數(shù)據(jù)寫入到文件里。
public void Write()
{
FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
//獲得字節(jié)數(shù)組
byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
//開始寫入
fs.Write(data, 0, data.Length);
//清空緩沖區(qū)、關閉流
fs.Flush();
fs.Close();
}
(2).使用FileStream類創(chuàng)建文件,使用StreamWriter類,將數(shù)據(jù)寫入到文件。
public void Write(string path)
{
FileStream fs = new FileStream(path, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//開始寫入
sw.Write("Hello World!!!!");
//清空緩沖區(qū)
sw.Flush();
//關閉流
sw.Close();
fs.Close();
}
相關文章
C#通過PInvoke調用c++函數(shù)的備忘錄的實例詳解
這篇文章主要介紹了C#通過PInvoke調用c++函數(shù)的備忘錄的實例以及相關知識點內容,有興趣的朋友們學習下。2019-08-08
webBrowser執(zhí)行js的方法,并返回值,c#后臺取值的實現(xiàn)
下面小編就為大家?guī)硪黄獁ebBrowser執(zhí)行js的方法,并返回值,c#后臺取值的實現(xiàn)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12
Unity3D獲取當前鍵盤按鍵及Unity3D鼠標、鍵盤的基本操作
這篇文章主要介紹了Unity3D獲取當前鍵盤按鍵及Unity3D鼠標、鍵盤的基本操作的相關資料,需要的朋友可以參考下2015-11-11
C#如何正確實現(xiàn)一個自定義異常Exception
這篇文章主要為大家詳細介紹了C#如何正確實現(xiàn)一個自定義異常Exception,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學習一下2023-09-09

