Vlad781
Vlad781

Reputation: 37

Read a specific line in a file

I know this has been answered several times before. But I am asking this for C#. Whereas there were a few for java. There was another one for C#, but it got me nowhere. So please do not rate poorly as I have a reason for this. Thank you.

My ultimate goal is to have a settings feature in my application. And I want all these settings to be saved into a text file. And when the application opens, it will automatically read that file and adjust the controls on my form.

I am unsure of where to start, but I was wondering if there was something along the lines of

String readLine(File file, int lineNumber)

Thank you in advance.

I already have a file being saved, and a file being opened. But I only have one setting saved in there. And that takes the first line. But if I want to add more controls being saved, rather than making a new file per option, I'd like to place several lines in that file, and each line would have its own control that it would change.

So, how can I read a specific line of a text file?

Thanks once again.

Upvotes: 2

Views: 8378

Answers (3)

parapura rajkumar
parapura rajkumar

Reputation: 24413

If you want a settings feature use the default and don't roll your own. You will only run into more issues with parsing and upgrade and finding a place to save it so that it can be modified when users are running under UAC or non admin accounts

Upvotes: 2

Eric J.
Eric J.

Reputation: 150198

Principally one must read each line of a text file to locate a specific line (stopping at that line if desired) because each text line can be of a different length, so you can't just compute an offset in the file and go there.

If this really is a configuration file (which presumably isn't huge, you could just use

string[] lines = File.ReadAllLines(myPath);

http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

That way all of the lines of the file are read into lines and you can access an individual line like

string line = lines[2];

If you really only want to read a specific line (keep in mind this will be very inefficient if you read multiple lines over time in your app because you keep re-reading from the start of the file), you will have to write your own helper routine.

Upvotes: 3

Ry-
Ry-

Reputation: 225164

Unless all the lines are exactly the same length, you can't just skip to a certain line number in the file. If you'll be needing most of the options, just read the file as an array of lines using System.IO.File.ReadAllLines:

string[] lines = File.ReadAllLines("myfile.txt");

Then you can just access each line like you would normally, say lines[1] for the second line.

Also, if you don't need to modify these settings with anything else, just use the built-in settings. They handle everything for you.

Upvotes: 2

Related Questions