473,772 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Determine File Encoding

Hi there,

Can anyone point out any really obvious flaws in the methodology below
to determine the likely encoding of a file, please? I know the number
of types of encoding is small, but that is only because the
possibilities I need to work with is a small list.
private string determineFileEn coding(FileStre am strm)
{
long originalSize = strm.Length;
StreamReader rdr = new StreamReader(st rm);

strm.Position = 0;
System.Text.UTF 8Encoding unic = new System.Text.UTF 8Encoding();
byte[] inputFile = unic.GetBytes(r dr.ReadToEnd()) ;
if(inputFile.Le ngth == originalSize)
{
return "UTF8";
}

strm.Position = 0;
System.Text.Uni codeEncoding unic2 = new System.Text.Uni codeEncoding();
byte[] inputFile2 = unic2.GetBytes( rdr.ReadToEnd() );
if(inputFile2.L ength == originalSize)
{
return "Unicode";
}

strm.Position = 0;
System.Text.UTF 7Encoding unic3 = new System.Text.UTF 7Encoding();
byte[] inputFile3 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile3.L ength == originalSize)
{
return "UTF7";
}

System.Text.ASC IIEncoding unic4 = new System.Text.ASC IIEncoding();
byte[] inputFile4 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile4.L ength == originalSize)
{
return "Ascii";
}

return "Not known";
}


Thanks in advance
Marc.
Nov 17 '05 #1
10 10100
Why read the entire file to determine the encoding. Can't you tell from the
indicator bytes at the beginning?

Forgive me if I don't know much about encoding, but your algorithm appears
wildly inefficient on its face.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Marc Jennings" <Ma**********@c ommunity.nospam > wrote in message
news:ch******** *************** *********@4ax.c om...
Hi there,

Can anyone point out any really obvious flaws in the methodology below
to determine the likely encoding of a file, please? I know the number
of types of encoding is small, but that is only because the
possibilities I need to work with is a small list.
private string determineFileEn coding(FileStre am strm)
{
long originalSize = strm.Length;
StreamReader rdr = new StreamReader(st rm);

strm.Position = 0;
System.Text.UTF 8Encoding unic = new System.Text.UTF 8Encoding();
byte[] inputFile = unic.GetBytes(r dr.ReadToEnd()) ;
if(inputFile.Le ngth == originalSize)
{
return "UTF8";
}

strm.Position = 0;
System.Text.Uni codeEncoding unic2 = new System.Text.Uni codeEncoding();
byte[] inputFile2 = unic2.GetBytes( rdr.ReadToEnd() );
if(inputFile2.L ength == originalSize)
{
return "Unicode";
}

strm.Position = 0;
System.Text.UTF 7Encoding unic3 = new System.Text.UTF 7Encoding();
byte[] inputFile3 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile3.L ength == originalSize)
{
return "UTF7";
}

System.Text.ASC IIEncoding unic4 = new System.Text.ASC IIEncoding();
byte[] inputFile4 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile4.L ength == originalSize)
{
return "Ascii";
}

return "Not known";
}


Thanks in advance
Marc.

Nov 17 '05 #2
I have to forgive you for not knowing too much about encoding. I know
even less. I agree that the algorithm *is* wildly inneficient, but
the fact is that I have not got a clue. :-) Such are the joys of
learning from Google.

On Wed, 1 Jun 2005 06:27:22 -0700, "Nick Malik [Microsoft]"
<ni*******@hotm ail.nospam.com> wrote:
Why read the entire file to determine the encoding. Can't you tell from the
indicator bytes at the beginning?

Forgive me if I don't know much about encoding, but your algorithm appears
wildly inefficient on its face.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representati ve of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.


Nov 17 '05 #3
KH
Check out the StreamReader constructors that take a bool argument to
determine the encoding from the byte order mark. Also check out the
Encoding.GetPre amble() method.
"Marc Jennings" wrote:
I have to forgive you for not knowing too much about encoding. I know
even less. I agree that the algorithm *is* wildly inneficient, but
the fact is that I have not got a clue. :-) Such are the joys of
learning from Google.

On Wed, 1 Jun 2005 06:27:22 -0700, "Nick Malik [Microsoft]"
<ni*******@hotm ail.nospam.com> wrote:
Why read the entire file to determine the encoding. Can't you tell from the
indicator bytes at the beginning?

Forgive me if I don't know much about encoding, but your algorithm appears
wildly inefficient on its face.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representati ve of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.


Nov 17 '05 #4
Marc Jennings wrote:
Hi there,

Can anyone point out any really obvious flaws in the methodology below
to determine the likely encoding of a file, please? I know the number
of types of encoding is small, but that is only because the
possibilities I need to work with is a small list.
private string determineFileEn coding(FileStre am strm)
{
long originalSize = strm.Length;
StreamReader rdr = new StreamReader(st rm);

strm.Position = 0;
System.Text.UTF 8Encoding unic = new System.Text.UTF 8Encoding();
byte[] inputFile = unic.GetBytes(r dr.ReadToEnd()) ;
if(inputFile.Le ngth == originalSize)
{
return "UTF8";
}

strm.Position = 0;
System.Text.Uni codeEncoding unic2 = new
System.Text.Uni codeEncoding(); byte[] inputFile2 =
unic2.GetBytes( rdr.ReadToEnd() ); if(inputFile2.L ength ==
originalSize) {
return "Unicode";
}

strm.Position = 0;
System.Text.UTF 7Encoding unic3 = new System.Text.UTF 7Encoding();
byte[] inputFile3 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile3.L ength == originalSize)
{
return "UTF7";
}

System.Text.ASC IIEncoding unic4 = new System.Text.ASC IIEncoding();
byte[] inputFile4 = unic3.GetBytes( rdr.ReadToEnd() );
if(inputFile4.L ength == originalSize)
{
return "Ascii";
}

return "Not known";
}


The most obvious flaw would be that generally speaking this is
impossible to achieve ;-)

The second flaw is that your code is just plain wrong. You're using a
UTF-8 StreamReader regardless of the actual encoding. This object will
be able to read UTF-8 and ASCII, but UTF-16 will break for sure.

The third flaw is that you assume "the number of types of encoding is
small". I'd say
http://msdn.microsoft.com/library/de.../en-us/intl/un
icode_81rn.asp is not really a short list, although many of these
encodings are not likely to be found in your typical American or
Western European PC environment.

Cheers,
--
http://www.joergjooss.de
mailto:ne****** **@joergjooss.d e
Nov 17 '05 #5
KH wrote:
Check out the StreamReader constructors that take a bool argument to
determine the encoding from the byte order mark. Also check out the
Encoding.GetPre amble() method.


That works only for certain UTFs and maybe some rather obscure stuff,
but today's popular 8 bit encodings like ISO-8859-x or Windows-152x
don't use preambles or BOMs.

Cheers,
--
http://www.joergjooss.de
mailto:ne****** **@joergjooss.d e
Nov 17 '05 #6
On Wed, 01 Jun 2005 11:59:09 -0700, "Joerg Jooss"
<ne********@joe rgjooss.de> wrote:

**snip**

The most obvious flaw would be that generally speaking this is
impossible to achieve ;-)

The second flaw is that your code is just plain wrong. You're using a
UTF-8 StreamReader regardless of the actual encoding. This object will
be able to read UTF-8 and ASCII, but UTF-16 will break for sure.

The third flaw is that you assume "the number of types of encoding is
small". I'd say
http://msdn.microsoft.com/library/de.../en-us/intl/un
icode_81rn.a sp is not really a short list, although many of these
encodings are not likely to be found in your typical American or
Western European PC environment.

Cheers,


Agreed in the general case, but perhaps I should have made my
situation a little clearer. The files that I need to deal with will
only be one of a very small subset of all the possible encodings out
there.

At least now I know my thinking is more flawed than I though it
was....
Nov 17 '05 #7
There is no way to determine the encoding of the file unless you know
exactly the text which you expect in the file or there are marker bytes in
the file or a special file extension.
But you can try to use a statistic approach. If the bytes on even positions
are mostly bigger than bytes on uneven positions (or was it the other way
around?) you have unicode. if there are no null chars and no chars < ascii
#32 except \r and \n you have certainly ascii encoding.
In all other cases you may have UTF8.

"Marc Jennings" <Ma**********@c ommunity.nospam > schrieb im Newsbeitrag
news:56******** *************** *********@4ax.c om...
On Wed, 01 Jun 2005 11:59:09 -0700, "Joerg Jooss"
<ne********@joe rgjooss.de> wrote:

**snip**

The most obvious flaw would be that generally speaking this is
impossible to achieve ;-)

The second flaw is that your code is just plain wrong. You're using a
UTF-8 StreamReader regardless of the actual encoding. This object will
be able to read UTF-8 and ASCII, but UTF-16 will break for sure.

The third flaw is that you assume "the number of types of encoding is
small". I'd say
http://msdn.microsoft.com/library/de.../en-us/intl/un
icode_81rn.a sp is not really a short list, although many of these
encodings are not likely to be found in your typical American or
Western European PC environment.

Cheers,


Agreed in the general case, but perhaps I should have made my
situation a little clearer. The files that I need to deal with will
only be one of a very small subset of all the possible encodings out
there.

At least now I know my thinking is more flawed than I though it
was....

Nov 17 '05 #8
Marc Jennings wrote:
On Wed, 01 Jun 2005 11:59:09 -0700, "Joerg Jooss"
<ne********@joe rgjooss.de> wrote:

**snip**

The most obvious flaw would be that generally speaking this is
impossible to achieve ;-)

The second flaw is that your code is just plain wrong. You're using
a UTF-8 StreamReader regardless of the actual encoding. This object
will be able to read UTF-8 and ASCII, but UTF-16 will break for
sure.

The third flaw is that you assume "the number of types of encoding
is small". I'd say
http://msdn.microsoft.com/library/de...rary/en-us/int
l/un icode_81rn.asp is not really a short list, although many of
these encodings are not likely to be found in your typical American
or Western European PC environment.

Cheers,


Agreed in the general case, but perhaps I should have made my
situation a little clearer. The files that I need to deal with will
only be one of a very small subset of all the possible encodings out
there.

At least now I know my thinking is more flawed than I though it
was....


The best approach is to have some kind of "protocol", that allows to
transports meta data like character encoding. If this is not possible
(as in the case of plain files), let the user decide by allowing him or
her to select and switch all supported between all supported encodings.

Cheers,
--
http://www.joergjooss.de
mailto:ne****** **@joergjooss.d e
Nov 17 '05 #9
Hello Marc,

If you open a file using StreamReader it will load a CurrentEncoding
with the correct file encoding and convert the bytes to the correct
characters.

"Joerg Jooss" wrote:
Marc Jennings wrote:
On Wed, 01 Jun 2005 11:59:09 -0700, "Joerg Jooss"
<ne********@joe rgjooss.de> wrote:

**snip**

The most obvious flaw would be that generally speaking this is
impossible to achieve ;-)

The second flaw is that your code is just plain wrong. You're using
a UTF-8 StreamReader regardless of the actual encoding. This object
will be able to read UTF-8 and ASCII, but UTF-16 will break for
sure.

The third flaw is that you assume "the number of types of encoding
is small". I'd say
http://msdn.microsoft.com/library/de...rary/en-us/int
l/un icode_81rn.asp is not really a short list, although many of
these encodings are not likely to be found in your typical American
or Western European PC environment.

Cheers,


Agreed in the general case, but perhaps I should have made my
situation a little clearer. The files that I need to deal with will
only be one of a very small subset of all the possible encodings out
there.

At least now I know my thinking is more flawed than I though it
was....


The best approach is to have some kind of "protocol", that allows to
transports meta data like character encoding. If this is not possible
(as in the case of plain files), let the user decide by allowing him or
her to select and switch all supported between all supported encodings.

Cheers,
--
http://www.joergjooss.de
mailto:ne****** **@joergjooss.d e

Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6866
by: jamie | last post by:
I have a file that was generated on a customers computer which is not using the Windows default text encoding but uses Japanese(Shift-JIS) encoding. If I open the file in notepad the data looks normal but my application can not read in the data properly (Line breaks are not what is expected) Is there a way to translate a file to the windows default text encoding? Also, is there an API to determine the which encoding a system is using?
0
1767
by: Merav | last post by:
I'm running a java application from Eclipse. Looking at the system properties I get the following values: file.encoding = Cp1255 user.language = iw user.country = IL Than I'm building a jar for the application and running the jar. Looking at the system properties I get the following values: file.encoding = Cp1252 user.language = en
2
1820
by: Matthew Mueller | last post by:
I noticed in python2.3 printing unicode to an appropriate terminal actually works. But using sys.stdout.write doesn't. Ex: Python 2.3.4 (#2, May 29 2004, 03:31:27) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> sys.stdout.encoding 'UTF-8' >>> u=u'\u3053\u3093\u306b\u3061\u308f'
1
10146
by: Gaia C via .NET 247 | last post by:
Hi All, How can i found out at what encoding the file was saved? I tried usign GetPreamble(), but for this i should already create a stream which get an encoding... StreamReader sr = new StreamReader(path); sr.CurrentEncoding.GetPreamble(); any idea? Thanks,
8
7586
by: Xarky | last post by:
Hi, I am downloading a GIF file(as a mail attachement) with this file format, Content-Transfer-Encoding: base64; Now I am writing the downloaded data to a file with this technique: streamWriter = new StreamWriter(@startupPath+"\\"+filename, false); streamWriter.WriteLine(data); I am not specifying any file Encoding. When I try to open the file
0
1551
by: Thomas Podlesak | last post by:
I need a function to determine if a file is utf-8 encoded. I found the inconv- and recode-functions. But they only seem to convert files. Isn´t there any php-function similar to the 'file'-command on linux?
3
1494
by: tomislav.vujnovac | last post by:
I need to generate xml file with data from ms sql server. That xml is used in some third party java program. That program need xml file that is saved as "windows-1250" but in first line is: "<?xml version="1.0" encoding="UTF-8"?>" When I make xml file as UTF-8, I can not open it with that java program, but when I make as "windows-1250" than I can open it but I can not see CE characters Tomislav
19
2594
by: Edward K. Ream | last post by:
Following the usual cookbook examples, my app parses an open file as follows:: parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_external_ges,1) # Hopefully the content handler can figure out the encoding from the <?xml>
3
2955
by: Sun | last post by:
Hi everyone . I have two files named a.txt and b.txt. I open a.txt with ultraeditor.exe. here is the first row of the file: neu für then I switch to the HEX mode: 00000000h: FF FE 6E 00 65 00 75 00 20 00 66 00 FC 00 72 00 20 00 0A 00 0D 00
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7461
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6716
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.