C#读取中文文件乱码的解方法的代码
时间: 2024-03-03 22:48:45 浏览: 30
以下是读取中文文件乱码的解决方法的C#代码:
```csharp
using System;
using System.IO;
using System.Text;
class Program
{
static void Main(string[] args)
{
string filePath = "中文文件路径";
string content = ReadText(filePath, Encoding.GetEncoding("gb2312"));
Console.WriteLine(content);
}
static string ReadText(string filePath, Encoding encoding)
{
string result = string.Empty;
try
{
using (StreamReader sr = new StreamReader(filePath, encoding))
{
result = sr.ReadToEnd();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return result;
}
}
```
在上面的代码中,使用了 StreamReader 来读取文件,并且指定了文件的编码格式为 GB2312,也可以根据实际情况选择其他编码格式。如果文件编码格式不正确,可能会出现乱码问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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_column_c1.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)