首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

C#使用文本文件

以下是关于C#使用文本文件的完善且全面的答案:

C#是一种面向对象的编程语言,它可以方便地处理文本文件。以下是一些常见的文本文件操作:

  1. 读取文本文件

可以使用System.IO.File.ReadAllText方法读取整个文本文件,或者使用System.IO.File.ReadAllLines方法读取文本文件的每一行。

代码语言:csharp
复制
string filePath = "example.txt";
string text = System.IO.File.ReadAllText(filePath);
string[] lines = System.IO.File.ReadAllLines(filePath);
  1. 写入文本文件

可以使用System.IO.File.WriteAllText方法写入整个文本文件,或者使用System.IO.File.WriteAllLines方法写入文本文件的每一行。

代码语言:csharp
复制
string filePath = "example.txt";
string text = "This is an example text.";
System.IO.File.WriteAllText(filePath, text);
string[] lines = new string[] { "This is an example text.", "This is the second line." };
System.IO.File.WriteAllLines(filePath, lines);
  1. 逐行读取文本文件

可以使用System.IO.StreamReader类逐行读取文本文件。

代码语言:csharp
复制
string filePath = "example.txt";
using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
  1. 逐行写入文本文件

可以使用System.IO.StreamWriter类逐行写入文本文件。

代码语言:csharp
复制
string filePath = "example.txt";
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
{
    writer.WriteLine("This is an example text.");
    writer.WriteLine("This is the second line.");
}

以上是一些常见的文本文件操作,可以方便地处理文本文件。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券