Read words into an array in C#

2019-09-19 11:40发布

问题:

I am trying to read a list of words into an array. I have read some tutorials and other questions on this site and am still stuck. It is probably something simple that I am missing but I can't figure it out.

Here is my code:

string badWordsFilePath = openFileDialog2.FileName.ToString();
                badWords = badWordsFilePath.Split(' ');
                MessageBox.Show("Words have been imported!");
                BadWordsImported = true;

What I want to happen is for all the words in the file to be put one by one into the array badWords.

Any ideas what I am doing wrong?

回答1:

Your code is not reading the file, it's splitting the "words" in the file path.

What you need to do is actually read the file.

string badWordsFilePath = openFileDialog2.FileName;
string fileContents = File.ReadAllText(badWordsFilePath);
badWords = fileContents.Split(' ');


回答2:

You should read the contents of the file into a variable. You're simply taking the filename and splitting that.

using (StreamReader sr = new StreamReader(openFileDialog2.FileName))
{
  string line = sr.ReadToEnd();
  badWords = line.Split(' ');
}


回答3:

openFileDialog2.FileName doesn't open the file. It's just a property that returns the name of the file selected in that Open File Dialog component.

You have to actually open the file to read from it. And then read it's contents. You could use the StreamReader class for that. For a simple example look at the sample included with the documentation of the ReadToEnd method.