我有一个程序打开.txt文件并将其存储到数组中。如果该文件包含的内容不是每行一个数字以外的内容,则会出现错误并且程序崩溃。我想知道是否有办法防止这种情况发生,并在用户的文件无效时给用户一条消息。错误检查文件c#
public void Load_Button_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0; // Reset progress bar
List<int> list = new List<int>();
OpenFileDialog ofd = new OpenFileDialog(); // Initialize open file dialog
ofd.Filter = "TXT File|*.txt"; // Set acceptable files
ofd.Title = "Open File";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Open the selected file to read.
string[] lines = File.ReadAllLines(ofd.FileName); // Read all lines in data file selected
dataArray = new int[lines.Length];
for (int i = 0; i < dataArray.Length; ++i)
{
dataArray[i] = int.Parse(lines[i]); // Add data to dataArray array
Unsorted_Box.Text += lines[i] + ", "; // Add data to unsorted box
}// end for
}
}
ÿ你正在寻找一个'catch'块或'int.TryParse'。 – SLaks