Luke101
Luke101

Reputation: 65238

How to represent a TextFile as an Array

I have a text file full of stopwords. I would like to represent this file as an array. I dont want to convert the file into an array on the fly - I want create code (code generation) or represent the text file as

var stopwordsarr = new string[] {"stopword1", "stopword2", "stopword3", "etc.."};

Does anyone know an easy way to do this?

Upvotes: 0

Views: 84

Answers (3)

rossipedia
rossipedia

Reputation: 59367

If you want to generate code, whip up a small Console app like so:

static void Main(string[] args) {
  var fname = args[0];
  var words = File.ReadAllLines(fname);

  Console.WriteLine("var stopWords = new string[] {");
  for(int i = 0; i < words.Length; ++i) {
    string word = words[i];
    Console.Write("@\"{0}\"", word.Replace("\"", "\\\""));
    if(i < words.Length - 1) {
      Console.Write(",");
    }
    Console.WriteLine();
  }
  Console.WriteLine("};");
}

Then you can just to: makestopwords.exe somefile.txt > stopwords.cs and voila

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134801

Assuming the file has the words listed on separate lines:

var stopWordsArr = File.ReadAllLines(path);

Upvotes: 2

jb.
jb.

Reputation: 10331

Do you just want File.ReadAllLines() ?

Upvotes: 1

Related Questions