检查文件时出错#

时间:2016-01-24 02:20:43

标签: c#

我有一个打开.txt文件并将其存储到数组中的程序。如果文件包含除每行一个数字以外的任何数字,则会出现错误并且程序崩溃。我想知道是否有办法防止这种情况发生,如果用户的文件无效,则会向用户发送消息。

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 
        }
    }

2 个答案:

答案 0 :(得分:1)

使用int.TryParse():

for (int i = 0; i < dataArray.Length; ++i)           
{                  
    if (!int.TryParse(lines[i],out dataArray[i]) // Add data to dataArray array 
    { 
       // do something about the invalid data - message / ignore  etc..
    }
    Unsorted_Box.Text += lines[i] + ", "; // Add data to unsorted box 

}// end for 

答案 1 :(得分:1)

  

你知道我怎么会错误检查这一行:
  var result2 = text.Split(“\ r \ n”.ToCharArray(),StringSplitOptions.RemoveEmptyEntries)?. Select(num =&gt; double.Parse(num))。OrderBy(d =&gt; d)。ToArray() ;“

var result2 = text.Split(" \r\n".ToCharArray(), 
        StringSplitOptions.RemoveEmptyEntries)?.Select(num => 
         { 
            double result;  
            if (!double.TryParse(num, out result))
            { // error set result to value other than zero if you need to }
            return result;
         }).OrderBy(d => d).ToArray();"