Problem reading special characters into a list box

Z

Zach

Using the code below I want to read a list of French words into the list
box. However the code dysfunctions because of the é, à etcetera in the
file that is being read. Could someone tell me how to rewrite the code
to ameliorate this problem?

Presumably this code needs to be amended:
while ((line = sr.ReadLine())!= null)

Presumably with Iformatprovider,
but I don't know how to do that.

Please be explicit.

Thank you,
Zach.

void fillListBox()
{
ArrayList words = new ArrayList();
try
{
string file_string = "data.txt";
using (StreamReader sr = new StreamReader(file_string))
{
String line;
while ((line = sr.ReadLine())!= null)
{
int pos = 0;
pos = line.IndexOf(":");
listBox1.Items.Add(line.Substring(0,pos));
}
}
}
catch
{
}
}
 
A

Alberto Poblacion

Zach said:
Using the code below I want to read a list of French words into the list
box. However the code dysfunctions because of the é, à etcetera in the
file that is being read. Could someone tell me how to rewrite the code
to ameliorate this problem?
[...]
using (StreamReader sr = new StreamReader(file_string))
[...]

Your problem is in the line that I quote. When opening the StreamReader,
you need to specify the character set in which the file is encoded, so that
the StreamReader can properly translate them into the Unicode encoding that
..Net uses internally.

using System.Text;
....
Encoding enc = Encoding.GetEncoding(1252);
using (StreamReader sr = new StreamReader(file_string, enc))
....

In the lines above I have used the encoding 1252, which is probably the one
that your file is using if it was written under a French version of Windows.
If this encoding doesn't work, you will need to determine which format is
being written by the program that created the file.
 
Z

Zach

Alberto said:
Zach said:
Using the code below I want to read a list of French words into the
list box. However the code dysfunctions because of the é, à etcetera
in the
file that is being read. Could someone tell me how to rewrite the code
to ameliorate this problem?
[...]
using (StreamReader sr = new StreamReader(file_string))
[...]

Your problem is in the line that I quote. When opening the
StreamReader, you need to specify the character set in which the file is
encoded, so that the StreamReader can properly translate them into the
Unicode encoding that .Net uses internally.

using System.Text;
...
Encoding enc = Encoding.GetEncoding(1252);
using (StreamReader sr = new StreamReader(file_string, enc))
...

In the lines above I have used the encoding 1252, which is probably the
one that your file is using if it was written under a French version of
Windows. If this encoding doesn't work, you will need to determine which
format is being written by the program that created the file.

The *.txt file was created under a normal UK/US version of Windows.
Your solution works OK though.

Many thanks,
Zach.
 
Top