Search code examples
c#arraystrim

Trimming every line in a text file then saving the result to an array


I need to read a local text file which will have a file name on every line. Every file name needs to be trimmed of it's extension. When I get to the part where I need to save the result of the trimming to another array I'm having some trouble.

So far I have:

string path = @"C:\Users\path\file.txt";

      string[] readText = File.ReadAllLines(path);
      foreach (string s in readText)
      {
          string result = Path.GetFileNameWithoutExtension(s);

          //here I can print the result to the screen 
          //but I don't know how to save to another array for further manipulation    

      }

If you need any further clarification I will do my best to be more clear. Thanks in advance.


Solution

  • Use a for loop instead of foreach:

    string path = @"C:\Users\path\file.txt";
    string[] readText = File.ReadAllLines(path);
    for( int i = 0; i < readText.Length; i++ )
        readText[i] = Path.GetFileNameWithoutExtension( readText[i] );