问题
I am getting an error use unassigned local variable 'multidimension' from below code. I am trying to put the data returned back from the text file in a multidimensional array by splitting them and put each row in in the array
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= null;
string ReadFromReadLine;
while ((ReadFromReadLine = sr.ReadLine()) != null)
{
data = ReadFromReadLine.Split(',');
for (int i = 0; i <= ReadFromReadLine.Length; i++)
{
for (int j = 0; j <= data.Length; j++ )
{
string[,] multidimensional;
multidimensional[i, j] = data[j];
}
}
}
//foreach(string s in Lines)
//{
// EditItemComboBox.Items.Add(s);
//}
}
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");
}
}
Any Ideas what I am doing wrong?
回答1:
string[,] multidimensional;
should be:
string[,] multidimensional = new string[ReadFromReadLine.Length, data.Length];
and moved out of the for loops and maybe sent to a method, cached, or something
回答2:
You are just defining an array called 'multidimensional', but not assigning it to anything.
for (int j = 0; j <= data.Length; j++ )
{
string[,] multidimensional = new String[i,data.Length]
multidimensional[i, j] = data[j];
}
However, I am not sure I am following what you are trying to do in the innermost loop. You are defining a new array called 'multidimensional' each time you are looping through the elements in data and the old data is lost each time.
If 'multidimensional' is suppose to contain the contents of the entire file, you need to define it outside of the first loop, but to use an array like you are, you need to know the number of lines in your file. If you are using C#2 or greater, a List<> would be a better choice
var list = new List<String[]>();
while ((ReadFromReadLine = sr.ReadLine()) != null)
{
data = ReadFromReadLine.Split(',');
list.Add(data);
}
来源:https://stackoverflow.com/questions/7669026/use-unassigned-local-variable-multidimension