我有这个代码,我想知道是否有办法捕获,如果更新的文件包含除了由标签分隔的数字或每行只有一个数字。
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
答案 0 :(得分:0)
如果我按字面意思描述正确的文件格式,即文件可以是仅包含制表符分隔数字序列的单行,或者如果文件包含多行,则每行只能包含单个数字序列 -
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;
}
答案 1 :(得分:0)
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();