By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,122 Members | 1,508 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,122 IT Pros & Developers. It's quick & easy.

How to Read a Specific Line from A Text File?

P: 2
Hi, I'm writing a console program in order to make my own keyboard shortcuts.
Expand|Select|Wrap|Line Numbers
  1. ConsoleKeyInfo input;
  2.  
  3. do
  4. {
  5.        if (File.Exists("info.txt") == true) ; 
  6.        else Console.WriteLine("File not found! \nPress any key to try again..."); Console.ReadKey(true);
  7. } while (File.Exists("info.txt") == false);
  8.  
  9. StreamReader reader = new StreamReader("info.txt");
  10.  
  11. do
  12. {
  13.        input = Console.ReadKey(true);
  14.        if (input.Key == ConsoleKey.R && input.Modifiers == ConsoleModifiers.Control)
  15.        {
  16.              Process.Start(reader.ReadLine()); 
  17.        }
  18.        if (input.Key == ConsoleKey.B && input.Modifiers == ConsoleModifiers.Control)
  19.        {
  20.              Process.Start(reader.ReadLine());
  21.        }
  22. } while (input.Key != ConsoleKey.Escape);
I want (R+Ctrl) to process.start the first line of info.txt, while (B+Ctrl) only the second line.

Whether pressing (R+Ctrl) or (B+Ctrl), at the first press the console readlines the first line, and at the second keypress the console readlines the second line; afterwards since there is no third line, pressing those keys crashes the console.

Thanks for help.
Feb 13 '11 #1

✓ answered by Aimee Bailey

to read a specific line in a text file, use the following:

Expand|Select|Wrap|Line Numbers
  1. string filename = "test.txt";
  2.  
  3. if (File.Exists(filename))
  4. {
  5.     string[] lines = File.ReadAllLines(filename);
  6.     Console.WriteLine(lines[3]);
  7. }
  8.  
where 3 can be replaced with any line number (zero based).

Share this Question
Share on Google+
2 Replies


Aimee Bailey
Expert 100+
P: 197
to read a specific line in a text file, use the following:

Expand|Select|Wrap|Line Numbers
  1. string filename = "test.txt";
  2.  
  3. if (File.Exists(filename))
  4. {
  5.     string[] lines = File.ReadAllLines(filename);
  6.     Console.WriteLine(lines[3]);
  7. }
  8.  
where 3 can be replaced with any line number (zero based).
Feb 14 '11 #2

P: 2
Thank you very much...

I run the program; when I initially press (R+Ctrl) or (B+Ctrl), then the pressed key(s) are only Console.ReadKey(true)'ed as you can see on the sixth code line in the above code.

How to make that specific [Console.ReadKey(true)] on the 6th line to execute only if the the statement is false.
Feb 14 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.