2

What I would like to do is pick a line from a text file. That line number is corresponding with a local variable. So if the variable is 1, pick line one. The text file is in Resources and called nl_5.txt. After that the picked line (a word) should placed in a new array, but each letter should be placed at a new index. So if the variable is 1, line one is apple. Something like this:

string[] arr1 = new string[] { "a", "p", "p", "l", "e" }; (0=a 1=p 2=p 3=l 4=e)

If the local variable is changing to 2, line two should be read and the array should be changed with the other line (other word, other letters). How should I do this?

I found different variants like read the complete file or read specific lines who're defined, but I've tried a lot with no correct result.

int lineCount = File.ReadAllLines(@"C:\test.txt").Length;
int count = 0;


private void button1_Click(object sender, EventArgs e)
{
    var reader = File.OpenText(@"C:\test.txt");


    if (lineCount > count)
    {
        textBox1.Text = reader.ReadLine();
        count++;
    }
}
Donovan
  • 81
  • 10
  • Can you show us what you've tried? – Marco Scabbiolo Jul 14 '16 at 13:48
  • `File.ReadAllLines` gives you an array separated by lines. From there it's easy enough to match them with the variable. Then you can simply call `ToArray()` on the string. – Lennart Jul 14 '16 at 13:50
  • 1
    [How do I read a specified line in a text file?](http://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file) + [Split string into string array of single characters](http://stackoverflow.com/questions/9846948/split-string-into-string-array-of-single-characters) – Alex K. Jul 14 '16 at 13:51
  • @MarcoScabbiolo I added one of the too many (almost) things I tried. – Donovan Jul 14 '16 at 13:52

1 Answers1

2

First, let's obtain the word via Linq:

 int line = 3; // one based line number

 string word = File
   .ReadLines(@"C:\test.txt") //TODO: put actual file name here
   .Skip(line - 1) // zero based line number
   .FirstOrDefault();

Then convert word into the array

 string[] arr1 = word
   .Select(c => c.ToString())
   .ToArray(); 

If you have to read the file for many different line you can cache the file:

   // Simplest, not thread safe
   private static string[] file;

   // line is one-based
   private static string[] getMyArray(int line) {
     if (null == file)
       file = File.ReadAllLines(@"C:\test.txt");

     // In case you have data in resource as string
     // read it and (split) from the resource
     // if (null == file)
     //   file = Resources.MyString.Split(
     //     new String[] { Environment.NewLine }, StringSplitOptions.None);

     string word = (line >= 1 && line < file.Length - 1) ? file[line - 1] : null;

     if (null == word)
       return null; // or throw an exception

     return word
       .Select(c => c.ToString())
       .ToArray(); 
   } 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215