使用c sharp读取TXT文件的实例
时间: 2023-09-29 07:03:03 浏览: 56
以下是使用 C# 读取文本文件的示例代码:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
try
{
// 读取文本文件的路径
string filePath = @"C:\example.txt";
// 创建一个 StreamReader 对象来读取文件内容
using (StreamReader reader = new StreamReader(filePath))
{
// 读取文本文件的所有内容
string content = reader.ReadToEnd();
// 将读取的内容输出到控制台
Console.WriteLine(content);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件不存在!");
}
catch (Exception ex)
{
Console.WriteLine("发生了一个错误:{0}", ex.Message);
}
}
}
```
在上面的示例中,我们使用 `StreamReader` 类来读取指定路径下的文本文件。`using` 语句用于在读取完成后自动释放 `StreamReader` 对象,以避免资源泄漏。`ReadToEnd` 方法用于读取文件的所有内容,然后将其输出到控制台。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)