[英]Catching Error in File c#
我有這段代碼,我想知道是否有一種方法可以捕獲更新的文件中是否包含除制表符分隔的數字以外的任何內容,或者每行僅包含一個數字。
private void complexDataToolStripMenuItem_Click(object sender, EventArgs e)
{
this.progressBar1.Value = 0; // Reset progress bar
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|PROPL File (*.propl_1178)|*.propl_1178"; // Set acceptable files
ofd.Title = "Open File";
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var text = File.ReadAllText(ofd.FileName);
var result2 = text.Split(" \r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)?.Select(num => double.Parse(num)).OrderBy(d => d).ToArray();
for(int i = 0; i < result2.Length; i++)
{
if (Lines_Check.Checked == true && i >= Start_Line.Value - 1)
{
if (End_Check.Checked == false)
{
Sorted_Box.Text += result2[i] + ", ";
}
}// end if
if (Lines_Check.Checked == true && i >= Start_Line.Value - 1)
{
if (End_Check.Checked == true && i <= End_Line.Value - 1)
{
Sorted_Box.Text += result2[i] + ", ";
}
}
if (Lines_Check.Checked == false)
{
Sorted_Box.Text += result2[i] + ", ";
}
}
}
} // end complex data
如果我從字面上理解您對正確文件格式的描述,即文件可以是僅包含制表符分隔的數字序列的一行,或者如果文件包含多行,則每行只能包含一個數字序列-
var isValid = true;
if (lines.Length == 1)
{
// must be tab delimited list of numbers
isValid = lines[0].Split('\t').All(x => x.All(y => Char.IsDigit(y)));
}
else if (lines.Length > 1)
{
// each line must contain a digit sequence only
foreach (var line in lines)
{
isValid = line.All(z => Char.IsDigit(z));
if (!isValid)
break;
}
}
如果您所說的文件包含任意行,並且任何行可以包含任意數量的定界數字序列,並且允許使用額外的空格或制表符,甚至允許使用空行,那么對您所說的內容的更寬松的解釋是:
var isValid = true;
foreach (var line in lines)
{
isValid = line.Split('\t', ' ').Select(x => x.Trim()).All(y => y.All(z => Char.IsDigit(z)));
if (!isValid)
break;
}
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 System.Windows.Forms.MessageBox.Show("Invalid File Format!"); } return result; } ).OrderBy(d => d).ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.