Sempus Sempus - 1 year ago 226
C# Question

How to tell if a file is text-readable in C#

Part of a list of projects I'm doing is a little text-editor.

At one point, you can load all the sub directories and files in a given directory. The program will add each as a node in a TreeView.

What I want the functionality to be is to only add the files that are readable by a normal text reader.

This code currently adds it to the tree:

TreeNode navNode = new TreeNode();
navNode.Text = file.Name;
navNode.Tag = file.FullName;


I know I could easily create an if statement with something like:


but I would have to expand that statement to contain every single extension that it could possibly be.

Is there an easier way to do this? I'm thinking it may have something to do with the mime types or file encoding.

Answer Source

There is no general way of figuring type of information stored in the file.

Even if you know in advance that it is some sort of text if you don't know what encoding was used to create file you may not be able to load it properly.

Note that HTTP give you some hints on type of file by content-type header, but there is no such information on file system.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download