Question XML files encoding

alexxutzu

New member
Joined
Apr 23, 2013
Messages
3
Programming Experience
1-3
Hi !


I have a problem loading an xml file into C#. I found out that this file has no predefined encoding type. When I open the xml file in Notepad++ I can see the data from the file. However, when I click the "Encoding" menu button, I see that there is no encoding set to this file. If I manually set the encoding of the file to "UTF-8", for example, I don't have the problem loading the xml in C# anymore.
Is there any way in which I can set the encoding of the file through C#, without doing it manually ? Thank you in advance !
 

alexxutzu

New member
Joined
Apr 23, 2013
Messages
3
Programming Experience
1-3
It works this way, but the problem is that i have hundreds of xml files, so it is almost impossible to set the encoding manually. Is it possible to set the encoding of a file automatically in C# ?
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,277
Location
Sydney, Australia
Programming Experience
10+
It works this way, but the problem is that i have hundreds of xml files, so it is almost impossible to set the encoding manually. Is it possible to set the encoding of a file automatically in C# ?
Do you actually know what the encoding of a file is? It's the mapping between the bytes in the file and the text that they represent. When you read the file you read the bytes and then use the encoding to convert that binary data to text. The application doesn't get to choose the encoding because the bytes in the file are the bytes in the file. If you don't use the correct encoding when reading the file then you get garbage. If you want a file to have a specific encoding then you have to save the file with that encoding. If you want to change the encoding then you have to read the file in using its current encoding and then save it out using the desired encoding. That's it, that's all.
 
Top Bottom