Read words into an array in C#

2019-09-19 11:37发布

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?

3条回答
Summer. ? 凉城
2楼-- · 2019-09-19 12:21

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.

查看更多
不美不萌又怎样
3楼-- · 2019-09-19 12:25

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(' ');
}
查看更多
Luminary・发光体
4楼-- · 2019-09-19 12:33

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(' ');
查看更多
登录 后发表回答