C#对txt文件进行读写操作
C#中对txt文件进行读写操作包括两种方式,一种是基于FileInfo类,调用该类的Read方法,但是该方法读出来的数据是byte格式,需要对其进行解码,将相应的字节数转换为字符,而C#中System.Text引用就包含的解码的方法,相应代码如下所示:
static void OpenFile(string filePath)
{
byte[] byteData = new byte[100];
char[] charData = new char[1000];
try
{
FileStream fileStream = new FileStream(filePath, FileMode.Open);
fileStream.Seek(0, SeekOrigin.Begin);
fileStream.Read(byteData, 0, 100);
Decoder decode = Encoding.Default.GetDecoder();
decode.GetChars(byteData, 0, byteData.Length, charData, 0);
Console.WriteLine(charData);
fileStream.Close();
}
catch(IOException e)
{
Console.WriteLine(e.ToString());
}
}
另一种读取方式是在FileInfo的基础上,使用StreamReader进行数据读取,使用这种方法不需要对数据在进行解码,因为该类在进行读取的时候已经完成的数据的解码,相应代码如下所示:
//open file with SteamReader
static void OpenFileWS(string filePath)
{
FileStream fileStream = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fileStream);
string line;
while((line=sr.ReadLine())!=null)
{
Console.WriteLine(line.ToString());
}
}
相应的对txt文件的写操作也包括两种,一种是基于FileInfo,如果写入的是字符串数据,需要预先对其进行编码,而后才能进行写入操作,代码如下所示:
//Write file with filesteam
static void WriteFS(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Create);
byte[] byteData = Encoding.Default.GetBytes("Hello World");
try
{
fs.Write(byteData, 0, byteData.Length);
fs.Flush();
fs.Close();
Console.WriteLine("Writing has been completed");
}
catch(IOException e)
{
Console.WriteLine(e.ToString());
}
}
而另外一种则是在FileInfo基础上,使用StreamWriter类,该种方法不需要经过编码便可直接将数据写入文本,因为该类的写操作中就包括了编码,相应代码如下:
//Write file with steamwrite
static void WriteWS(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
try
{
sw.WriteLine("Hello World!");
sw.Flush();
sw.Close();
fs.Close();
Console.WriteLine("Writing has been completed");
}
catch (IOException e)
{
sw.Flush();
sw.Close();
fs.Close();
Console.WriteLine(e.ToString());
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_62355555/article/details/125614726