读取在 C# 中编码的 [ANSI] 的文本文件

本文关键字:ANSI 文本 文件 读取 编码 | 更新日期: 2023-09-27 18:32:04

我的文本文件包含 ö、ä、ü 等字符,文件以 ANSI 编码。我想读取它并将所有数据放在数据表中。我的代码是:

    private DataTable GetTextToTable(string path)
    {
        try
        {
            DataTable dataTable = new DataTable();
            int rowNo = 0;
            using (StreamReader sr = new StreamReader(path,Encoding.Default,true))
            {
                DataRow dr = null;
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    dr=dataTable.NewRow();
                    if (rowNo == 0)
                    {
                        string[] Columns = line.Split(new string[] { "'t" }, StringSplitOptions.None);
                        for (int i = 0; i != Columns.Length; i++)
                        {
                            DataColumn dc = new DataColumn();
                            dc.ColumnName = Convert.ToString(Columns[i]);
                            dataTable.Columns.Add(dc);
                        }
                        rowNo = rowNo + 1;
                    }
                    else
                    {
                        string[] ColumnsValue = line.Split(new string[] { "'t" }, StringSplitOptions.None);
                        for (int i = 0; i != ColumnsValue.Length; i++)
                        {
                            dr[i] = ColumnsValue[i];
                        }
                        dataTable.Rows.Add(dr);
                    }
                }
            }
            return dataTable;
        }
        catch (Exception e)
        {
              throw new Exception(e.Message);
        }
    }

我从这段代码中得到的输出是:¿1/2 对于 ö,并以同样的方式为其余的 ä 获取任意字符组合,ü 类型字符也是如此。所以帮帮我!提前感谢!

读取在 C# 中编码的 [ANSI] 的文本文件

我的建议是下载类似WinHex的东西(是免费的),它可以让您以十六进制格式查看文件,这可能有助于您找到问题。

这只是一个猜测,但听起来您的程序正在读取原始十六进制,而不是被告知将其转换为 ASCII。编辑或者您正在从中读取的文件使用的任何编码格式。