读取文本
读取文本文件是C#中一个常见的任务。我们可以使用StreamReader
类来逐行读取文本文件。
逐行读取
下面的示例演示了如何逐行读取文本文件:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
using (StreamReader sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
在上面的示例中,我们使用StreamReader
类打开文本文件,并逐行读取文本。通过在while
循环中调用sr.ReadLine()
方法,我们可以逐行读取文件中的文本。每当调用该方法时,它将返回文件中的下一行。
全部读取
除了逐行读取文本之外,我们还可以使用File.ReadAllText()
方法将整个文本文件读入一个字符串中:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
string text = File.ReadAllText(path);
Console.WriteLine(text);
}
}
在上面的示例中,我们使用File.ReadAllText()
方法读取整个文本文件并将其存储在text
字符串变量中。然后,我们将字符串打印到控制台。
写入文本
与读取文本类似,写入文本文件也是C#中一个常见的任务。我们可以使用StreamWriter
类来逐行写入文本文件。
逐行写入
下面的示例演示了如何逐行写入文本文件:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("Hello");
sw.WriteLine("World");
}
}
}
在上面的示例中,我们使用StreamWriter
类打开文本文件,并逐行写入文本。通过在using
语句中创建StreamWriter
对象,我们可以确保在使用完后释放资源。
全部写入
除了逐行写入文本之外,我们还可以使用File.WriteAllText()
方法将整个字符串写入文本文件中:
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = @"C:\example.txt";
string text = "Hello\nWorld";
File.WriteAllText(path, text);
}
}
在上面的示例中,我们使用File.WriteAllText()
方法将整个字符串写入文本文件中。该方法需要两个参数:要写入的文件路径和要写入文件的内容。
更改文本文件编码
有时我们需要更改文本文件的编码。例如,我们可能需要将UTF-8编码的文本文件转换为UTF-16编码。我们