Try this modification of your first code: …new StreamReader(fsRead, ***Encoding.UTF8****)*.
how to read an ANSI file ?
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#
2 answers
Sort by: Most helpful
-
-
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 usedline = reader.ReadLine()