Search code examples
c#arraysfile.readalllines

Creating a string array that contains each line from a file in C#


I'm trying to create an application that confronts a string given in input by the user to a series of words written in the file. Each word is written on a different line without spaces between the lines. They look like this:

TEST

WORD

TEST2

And I would need the array to save them each with their own position so that if I used array[1] , I would get "WORD".

I have tried a few different methods but I can't make it work. Now I am trying to use the File.ReadLines command this way:

string[] wordlist;
string file = @"C:\file";
bool check = false;


if(File.Exists(file))
{
   wordlist = File.ReadLines(file).ToArray();
}

for(int i = 0; i < wordlist.Length && check == false; i++)
{
  if(wordInput == wordlist[i])
    check = true;
}

I don't understand if this turns the entire file into one big variable or if it just saves the lines not as strings but as something else


Solution

  • So you have wordInput and you want to check if file has such a line. You can query with a help of Linq, Any. Please, note, that in general case you can well have very long file which doesn't fit array (which should be below 2GB):

    using System.IO;
    using System.Linq;
    
    ...
    
    bool check = false;
    
    try {
      if (File.Exists(file))
        check = File
          .ReadLines(file)
          .Any(line => string.Equals(wordInput?.Trim(), 
                                     line, 
                                     StringComparison.OrdinalIgnoreCase));
    }
    catch (IOException) {
      ;
    }
    

    I've added ?.Trim() to wordInput since all the words in file are trimmed ("word is written on a different line without space"), but I am not sure if wordInput has unwanted leading and trailing spaces.