Reputation: 989
I need to access a file as text file and want to process it later. But before I fetch it how I can identify a file that I am taking is a text file only. If file is in another format my whole code interpret wrongly. I want to access and process only text file.
Currently i am using:
StreamReader objReader = new StreamReader(filePath);
How can I do so in C# .NET?
Upvotes: 0
Views: 385
Reputation: 24370
If file is in another format my whole code interpret wrongly.
Sure, if you expect a text file and end up getting a binary file your code will interpret it wrongly. But so is also the case for any invalid text file: what if it's not comma separated when you expect that? Or not json, when that's what you want? Or is in an encoding you can't handle?
The point is, unless you're just copying the text or doing something very low-level with it, you'll need more checking than text vs binary anyway. You should (probably) check that the entire file conforms to your needs. And that will catch any non-text files that are passed in to your program too!
Upvotes: 0
Reputation: 1503479
Well, there are heuristics you could apply:
But it's all heuristic, basically. At the end of the day, a file is a name and some bytes, along with some metadata about access permissions. In some file systems there can be more metadata available, but it's typically hard to get at and often not preserved when copying files around - so shouldn't be relied on for this.
Upvotes: 2
Reputation: 187110
If you want to get the extension of the file you can use
Path.GetExtension method
Upvotes: 0