Sara Sara - 1 year ago 116
C# Question

Not able to read special character "£" using Streamreader in c#

I am trying to read a character (

£
) from a text file, using the following code.

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;
}


But my code is not correctly reading
£
, It is reading the character as
please guide me what needs to be done to read the special character.

Thanks in advance.

Answer Source

Try to replace Encoding.Default with Encoding.GetEncoding(437)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download