how to read an ANSI file ?

jmclej2 1 Reputation point
2021-03-16T16:28:04.767+00:00

Hello,
I must extract data from a log file.
I use the folowing code :
FileStream fsRead = new FileStream(ConfigurationManager.AppSettings["inputLogFile"], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (fsRead != null)
{
using (StreamReader reader = new StreamReader(fsRead))
{
string line = "";
while ((line = reader.ReadLine()) != null)
{
...
if (line.Contains("Le paramètre 'toto' est requis"))
...
}
}
}
Like this, it doesn't work (I don't have an error but it can't recognize all my "line.Contains").
Opening this log file in Notepad++, the menu Encoding indicates it is ANSI.
If I copy/paste the content of the file in a new one where Notepad++ indicates that the encoding is UTF-8 and that I use the latter in my program, then it works well.
I am then looking for a way to modify my code so that I don't have to do this manual step in order to automate this task.
So I am looking to transform ANSI to UTF-8 by applying the following code .
There is not a specific Encoding.ANSI but the definition of Encoding.Default is :

Gets an encoding for the operating system's current ANSI code page

FileStream fsRead = new FileStream(ConfigurationManager.AppSettings["inputLogFile"], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (fsRead != null)
{
using (StreamReader reader = new StreamReader(fsRead, true))
{
string line = "";
while ((line = Encoding.UTF8.GetString(Encoding.Default.GetBytes(reader.ReadLine()))) != null)
{
...
if (line.Contains("Le paramètre 'toto' est requis"))
...
}
}
}
But this is still not working, I have this time the following error on the line of my "while"

System.ArgumentNullException : {"String reference not set to an instance of a String.\r\nName of parameter*: s"}

I am blocked because I don't see what I can do more to correctly read this ANSI file.
Thanks for your help.

Developer technologies C#
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2021-03-16T17:01:18.85+00:00

    Try this modification of your first code: …new StreamReader(fsRead, ***Encoding.UTF8****)*.

    1 person found this answer helpful.

  2. jmclej2 1 Reputation point
    2021-03-16T19:07:59.893+00:00

    I have tried another "mix" which worked : I opened the file using new StreamReader(fsRead, Encoding.Default) and used line = reader.ReadLine()

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.