File input in C#…

You would think that .Net being all fancy-like would have a function for pretty much everything. Apparently not.

I was messing around a little today with doing some file reading/writing for a configuration file in my latest attempt at playing around with XNA. In C you would do something like:

//do file opening stuff...
FILE *pFile;
int num;
fscanf(PFile, "%i", num);

Simple enough, right? Well, in C#, things are a bit different:

FileStream file = new FileStream("somefile.txt", FileMode.Open, FileAccess.Read);
StreamReader streamReader = new StreamReader(file);

//inside of a try block...
int BackBufferWidth;
int BackBufferHeight;
string[] linePart = streamReader.ReadLine().Split(new char[] { ' ' });
BackBufferWidth = Int32.Parse(linePart[0]);
BackBufferHeight = Int32.Parse(linePart[1]);

Call me bizare, but I prefer the C/C++ version. In C# you have to read in an entire line, then parse the string into pieces according to a delimiter, and do what you need to with the individual pieces. There is probably a better way, but I haven’t found it yet.

If you do know of a better way, please, let me know. I am all ears!

EDIT: Yes, I know I should probably use a StringBuilder, as strings are immutable. (That means each time a string is modified, an entirely new string is created. The old one is then gobbled up by the garbage collector. A new StringBuilder isn’t created each time a string is modified).



  1. JasonS

    For configuration files, it’s much easier to use .NET serialization. As for reading in a file line by line, I usually read in the whole file and then use regular expressions to manipulate the contents. It’s easy and takes little code.

  2. Joel

    Hmm, that is strange. I tried to post a reply to this and it didn’t appear…

    JasonS – you are most certainly right. For sake of curiosity I tried doing exactly that – I created a class to store all my settings, and flagged it as serializable. It was a snap to do, and worked like a charm. The only reason I don’t like doing that is you can’t easily manually edit binary data in config files. When working with text files it is quite easy to crack open Notepad (or your favourite text editor) and manually change your config files. When working with binary files, it isn’t nearly as simple.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s