You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中如何使用Windows-1252编码的XML文件填充DataGridView

在.NET Core中读取Windows-1252编码的XML并填充DataGridView

嘿,这个问题我碰到过好多次——.NET Core默认确实没内置Windows-1252(也算是ISO-8859-1的超集)的编码支持,但咱们几步就能搞定,完全不用绕弯路:

步骤1:安装编码扩展包

首先得通过NuGet装上System.Text.Encoding.CodePages包,它专门提供了.NET Core默认缺失的各种传统编码支持,其中就包括Windows-1252。

你可以直接用NuGet包管理器安装,或者在终端执行命令:

# .NET CLI命令
dotnet add package System.Text.Encoding.CodePages

要是用Package Manager Console的话:

Install-Package System.Text.Encoding.CodePages

步骤2:注册编码提供器

在应用启动的时候(比如Program.cs的Main方法里,或者WinForms窗体的构造函数初始化代码中),加一行代码注册编码提供器,这样.NET Core就能识别Windows-1252编码了:

using System.Text;

// 这个操作只需要执行一次,放在全局启动位置更高效
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

步骤3:读取XML并绑定到DataGridView

现在就能正常读取Windows-1252编码的XML文件了,给你个完整的WinForms示例,把XML读进DataSet再绑定到DataGridView:

using System.Data;
using System.Text;
using System.IO;

// 假设这是你的窗体代码
private void LoadXmlToGrid()
{
    // 保险起见,这里再检查下编码提供器是否注册(如果启动时没加可以在这里补)
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
    
    string xmlPath = @"C:\your-windows-1252-file.xml";
    Encoding win1252 = Encoding.GetEncoding(1252);
    
    // 用StreamReader指定编码读取XML
    using (StreamReader reader = new StreamReader(xmlPath, win1252))
    {
        DataSet dataSet = new DataSet();
        dataSet.ReadXml(reader);
        
        // 绑定到DataGridView,这里默认取XML里的第一个数据表
        if (dataSet.Tables.Count > 0)
        {
            dataGridView1.DataSource = dataSet.Tables[0];
        }
    }
}

额外注意点

  • 要确保XML文件的实际编码确实是Windows-1252,如果XML声明里写了encoding="windows-1252",那和咱们指定的编码一致就不会有乱码;
  • 如果XML是从网络流或者其他非文件来源获取的,同样可以用Encoding.GetEncoding(1252)来指定解码方式;
  • 编码提供器只需要注册一次,所以放在应用启动的全局位置更高效,不用每次读取都注册。

内容的提问来源于stack exchange,提问作者adnan Alyaari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:32:45