How to tell if file is text based

E

Elmo Watson

I want my application to load any file that is text based (php, txt, rtf,
asp, etc) - - just not any binary file
In the Open file dialog, that's easy, but I want users to be able to load
the files by drag/drop - - so therefore, I will need to check for the types
of files.
I could go through the different filetypes
if FILENAME.endswith(".txt"), etc, but that would end up being pretty
ridiculous

How can I check the file, as it comes in, as to whether it's text based or
binary?
 
L

Larry Smith

I want my application to load any file that is text based (php, txt, rtf,
asp, etc) - - just not any binary file
In the Open file dialog, that's easy, but I want users to be able to load
the files by drag/drop - - so therefore, I will need to check for the
types of files.
I could go through the different filetypes
if FILENAME.endswith(".txt"), etc, but that would end up being pretty
ridiculous

How can I check the file, as it comes in, as to whether it's text based or
binary?

You can't detect whether an arbitrary file contains text only without
actually inspecting the file. This isn't practical of course so the only
realistic way to accomplish your goal is to inspect the file type info
stored in the registry. Even here however you're at the mercy of whoever
registered the info. It might be incomplete for instance in which case you
can't determine if the file is text or not. In any case, I don't know all
the rules or functions involved in the process off-hand nor whether .NET
offers any direct way to handle this (without going through Win32 calls
directly). I would start my search however by having a look in the registry
under HKEY_CLASSES_ROOT\.txt (an extension exists under HKEY_CLASSES_ROOT
for all registered files). You'll see that the default value is "txtfile",
the "Content Type" is "text/plain" and the "PerceivedType" is "text ".
Researching these values should lead you down the path to accomplsih your
goal. Here's an important link for starters (read all sub-chapters as well):

http://msdn.microsoft.com/library/e...ing/fileassociations/fileassoc.asp?frame=true
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top