C#中对txt文件进行读写操作包括两种方式,一种是基于FileInfo类,调用该类的Read方法,但是该方法读出来的数据是byte格式,需要对其进行解码,将相应的字节数转换为字符,而C#中引用就包含的解码的方法,相应代码如下所示:
static void OpenFile(string filePath)
{
byte[] byteData = new byte[100];
char[] charData = new char[1000];
try
{
FileStream fileStream = new FileStream(filePath, );
(0, );
(byteData, 0, 100);
Decoder decode = ();
(byteData, 0, , charData, 0);
(charData);
();
}
catch(IOException e)
{
(());
}
}
另一种读取方式是在FileInfo的基础上,使用StreamReader进行数据读取,使用这种方法不需要对数据在进行解码,因为该类在进行读取的时候已经完成的数据的解码,相应代码如下所示:
//open file with SteamReader
static void OpenFileWS(string filePath)
{
FileStream fileStream = new FileStream(filePath, );
StreamReader sr = new StreamReader(fileStream);
string line;
while((line=())!=null)
{
(());
}
}
相应的对txt文件的写操作也包括两种,一种是基于FileInfo,如果写入的是字符串数据,需要预先对其进行编码,而后才能进行写入操作,代码如下所示:
//Write file with filesteam
static void WriteFS(string filePath)
{
FileStream fs = new FileStream(filePath, );
byte[] byteData = ("Hello World");
try
{
(byteData, 0, );
();
();
("Writing has been completed");
}
catch(IOException e)
{
(());
}
}
而另外一种则是在FileInfo基础上,使用StreamWriter类,该种方法不需要经过编码便可直接将数据写入文本,因为该类的写操作中就包括了编码,相应代码如下:
//Write file with steamwrite
static void WriteWS(string filePath)
{
FileStream fs = new FileStream(filePath, );
StreamWriter sw = new StreamWriter(fs);
try
{
("Hello World!");
();
();
();
("Writing has been completed");
}
catch (IOException e)
{
();
();
();
(());
}
}