我正在从文本文件中读取信息,我希望逐行浏览文本文件,并且在每一行中我想根据一个字符(例如',')将每个句子从另一个句子中分开,我想要将数据保存在一个数组中但是当我打印它时,我得到的只是最后一个结果。
private void button1_Click_1(object sender, EventArgs e)
{
string StringArray = null;
//to get the browsed file and get sure it is not curropted
try
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string data;
while ((data = sr.ReadLine()) != null)
{
StringArray = data.Split(',');
}
}
for (int i = 0; i < StringArray.Length; i++)
{
textBox1.Text = StringArray[i];
}
FilePath.Text = openFileDialog1.FileName;
textBox1.Text = (string)File.ReadAllText(FilePath.Text);
}
}
catch(IOException ex)
{
MessageBox.Show("there is an error" + ex+ "in the file please try again");
}
}
答案 0 :(得分:1)
这是您的错误:
上面你定义:
string StringArray = null;
然后您将其用作:
StringArray = information.ToString().Split(SplitCommas);
Split返回string []而不是字符串。你需要将顶部的声明改为..
string[] StringArray;
错误:“无法将类型字符串[]隐式转换为字符串”。应该给你提示你试图将字符串数组存储到字符串中。
答案 1 :(得分:0)
您需要将StringArray定义为String[]
string[] StringArray = null;
使用String.Split
而不是for循环
StringArray = data.Split(',');
答案 2 :(得分:0)
在你的第3行中,你将String数组声明为字符串,你应该将它声明为数组:
string [] StringArray = null;