1

I am reading lines from a CSV file using C#. However, the text that is read is incorrectly encoded. I have tried to convert it to UTF8 but to no avail.

string type_of_loan = System.Text.Encoding.UTF8.GetString(Encoding.GetEncoding("iso-8859-1").GetBytes(lineParts[5]));

I opened the file in an editor and it renders correctly when I open it using Western Latin 1 (iso-8859-1), but originally it says it is in Western Roman encoding and using that encoding I am getting the faulty characters to display as shown in the attached images.

Note that the weird question mark character shows up in C# even before it is saved to the DB.

I am expecting the swedish character "å" in its place.

incorrect text

correct text

6
  • Are you opening file like this : StreamReader reader = new StreamReader(@"c:\temp\test.txt", Encoding.GetEncoding("iso-8859-1")); when displaying character use RichTextBox not a regular text box. Commented Jul 1, 2017 at 13:41
  • Im jus reading the lines using: var linesInFile = sftp.ReadLines(file.FullName); Commented Jul 1, 2017 at 13:53
  • You need to apply the encoding at the source where your lineParts are coming from. If you are already reading them in the wrong format all special characters are already garbled or were replaced by substitute characters which cannot be reversed. Using GetBytes of one encoding and doing GetString with another encoding therefore in general can't work. There is a File.ReadLine(string, Encoding) overload which you should use. The File.ReadLine(string) overload assumes UTF-8. Commented Jul 1, 2017 at 13:56
  • Tried var linesInFile = sftp.ReadLines(file.FullName, Encoding.UTF8); Didnt work. Commented Jul 1, 2017 at 14:27
  • Encoding.GetEncoding("iso-8859-1") Worked! Commented Jul 1, 2017 at 14:31

1 Answer 1

1

This solved it:

var linesInFile = sftp.ReadLines(file.FullName, Encoding.GetEncoding("iso-8859-1"));

Thanks @ckuri

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.