openfiledialog getting data as multidimensional array with string split
i am reading a file from the openfiledialog. and it looks like this:
0001,pencil,planet office,0.05,1,20/n
0010,black pen,ribo,0.10,5,15/n
0011,blue pen,ribo,0.10,6,8/n
0012,red pen,ribo,0.12,8,3/n
1015,refill pad (lined),planet office,1.00,0,50/n
1016,refill pad (blank),pads are us,1.20,2,5/n
i want to put this information in a multidimensional array each row have 7 cols by using split method and this is my code and it is not working the error is "cannot implicitly convert type string to string[,]" i know that i am getti开发者_高级运维ng the data in an array not a multidimensional array but how can i read from the file as a multidimensional array with splitting each row from the comma.
private void button1_Click_1(object sender, EventArgs e)
{
string[,] Lines;
//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)
{
Lines = data;
}
}
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");
}
}
See my answer to one of your earlier questions for the same problem: use unassigned local variable 'multidimension'
I've updated it make it a bit more complete:
private void button1_Click_1(object sender, EventArgs e)
{
List<String> Lines = new List<String>();
try
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
while ((data = sr.ReadLine()) != null)
{
Lines.Add(data);
}
}
FilePath.Text = openFileDialog1.FileName;
}
}
catch(IOException ex)
{
MessageBox.Show("there is an error" + ex+ "in the file please try again");
}
}
You need to convert array of arrays to multidimensional. Use a list:
List<string[]> data = new List<string[]>();
string readFromReadLine;
while ((readFromReadLine= sr.ReadLine()) != null)
{
data.Add(readFromReadLine.Split(','));
}
string[,] lines = new string[data.Count,yourArrayLength];
//convert array of arrays to multidimensional
for (int x=0;x<data.Count;x++)
{
for (int y = 0; y < yourArrayLength; y++)
{
lines[x, y] = data[x][y];
}
}
StreamReader.ReadLine has the return type of string and data is a string[,], so when you attempt to assign data = StreamReader.ReadLine it complains about the type mismatch.
string[,] data;
string readFromReadLine;
while ((readFromReadLine= sr.ReadLine()) != null)
{
data = readFromReadLine.Split(.....);
//do other stuff here
}
精彩评论