Habip Oğuz
Habip Oğuz

Reputation: 1203

Character problem while getting information from vCard in C#

Here is my vCard content:

BEGIN:VCARD
VERSION:3.0
N:Büyükçarşıbaşıoğlu;Oğuz;;;
FN:BüyükçarşıbaşıoğluOğuz
ORG:;
TEL;CELL;VOICE:019365478236598742588952
END:VCARD

When I try to parse it like this:

var lines = File.ReadAllLines("test.vcf");
var get = lines.FirstOrDefault(x => x.StartsWith("N:"));  
var splt = get?.Replace("N:", "").Split(';').Where(x => !string.IsNullOrEmpty(x)).ToArray();

var first_name = splt != null && splt.Length > 1 ? string.Join(" ", splt.Skip(1).Take(5).ToArray()) : splt?[0];
var last_name = splt != null && splt.Length > 1 ? splt?[0] : string.Empty;

var result = !string.IsNullOrEmpty(last_name) ? first_name + " " + last_name : first_name;

MessageBox.Show(result);

It causes a problem with Turkish characters like this:

enter image description here

How can I solve the problem?

Upvotes: 1

Views: 339

Answers (1)

kamal m
kamal m

Reputation: 31

Please set encoding of file to utf-8. You can create a new file and save as utf-8, Otherwise you should get encoding of vCard file and tell the file reader.

For obtain encoding of the file you can use this method:

private static Encoding GetEncoding(string file)
{
    using (var reader = new StreamReader(file, Encoding.Default, true))
    {
        if (reader.Peek() >= 0)
            reader.Read();

        return reader.CurrentEncoding;
    }
}

and use it:

        var encoding = GetEncoding("yourfile");
        var lines = File.ReadAllLines("yourfile", encoding);

Upvotes: 3

Related Questions