检查文件 c# 时出错

本文关键字:出错 文件 检查 | 更新日期: 2023-09-27 18:31:39

我有一个程序可以打开一个.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 
        }
    }

检查文件 c# 时出错

使用 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 

你知道我将如何错误检查这一行吗:
var result2 = 文本。拆分(" ''r'".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)?.选择(数字 => 双精度。解析(数字))。OrderBy(d => 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();"