无法读取特殊字符"£"在c#中使用流阅读器
本文关键字:quot 读取 特殊字符 #163 | 更新日期: 2023-09-27 17:54:25
我试图从文本文件中读取一个字符(£
),使用以下代码。
public static List<string> ReadAllLines(string path, bool discardEmptyLines, bool doTrim)
{
var retVal = new List<string>();
if (string.IsNullOrEmpty(path) || !File.Exists(path)) {
Comm.File.Log.LogError("ReadAllLines", string.Format("Could not load file: {0}", path));
return retVal;
}
//StreamReader sr = null;
StreamReader sr = new StreamReader(path, Encoding.Default));
try {
sr = File.OpenText(path);
while (sr.Peek() >= 0) {
var line = sr.ReadLine();
if (discardEmptyLines && (line == null || string.IsNullOrEmpty(line.Trim()))) {
continue;
}
if (line != null) {
retVal.Add(doTrim ? line.Trim() : line);
}
}
}
catch (Exception ex) {
Comm.File.Log.LogGeneralException("ReadAllLines", ex);
}
finally {
if (sr != null) {
sr.Close();
}
}
return retVal;
}
但是我的代码没有正确读取£
,它正在读取�
字符,请指导我需要做什么来读取特殊字符。
您正在读取的文件的编码与Encoding.Default
不同。很可能是UTF-8。尝试对这个特定的文件使用UTF-8。要了解更多通用用法,请参见确定文本文件的编码。
尝试用Encoding.GetEncoding(437)
代替Encoding.Default
看起来像是编码问题。试着用UTF-8(或Unicode)编码来代替默认的StreamReader
。
StreamReader sr = new StreamReader(path, Encoding.UTF8));
可以通过两种方式向流阅读器提供编码信息:
1)保存您的文件与另存为选项,并选择适当的编码选项,从下拉窗口。看到截图2)如果你的文件是动态的,使用Encoding.GetEncoding()和StreamReader