打开文本文件,遍历内容并检查 [英] Open text file, loop through contents and check against
问题描述
所以我有一个我正在尝试实施的通用数字检查:
So I have a generic number check that I am trying to implement:
public static bool isNumberValid(string Number)
{
}
我想读取文本文件的内容(仅包含数字)并检查每一行的数字并使用 isNumberValid
验证它是有效数字.然后我想将结果输出到一个新的文本文件,我到此为止:
And I want to read the contents of a textfile (only contains numbers) and check each line for the number and verify it is the valid number using isNumberValid
. Then I want to output the results to a new textfile, I got this far:
private void button2_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
using (StringReader reader = new StringReader(text))
{
foreach (int number in text)
{
// check against isNumberValid
// write the results to a new textfile
}
}
}
catch (IOException)
{
}
}
}
如果有人可以提供帮助,是否会被困在这里?
Kind of stuck from here if anyone can help?
文本文件在列表中包含多个数字:
The textfile contains several numbers in a list:
4564
4565
4455
等
我想写的新文本文件只是在末尾附加真或假的数字:
The new textfile I want to write would just be the numbers with true or false appended to the end:
4564 真
推荐答案
你可以试试这个,以保持你最初遵循的模式......
You could try this to keep with the pattern you were initially following...
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
using (var reader = new StreamReader(file))
{
using (var writer = new StreamWriter("results.txt"))
{
string currentNumber;
while ((currentNumber = reader.ReadLine()) != null)
{
if (IsNumberValid(currentNumber))
writer.WriteLine(String.Format("{0} true", currentNumber));
}
}
}
}
catch (IOException)
{
}
}
}
public bool IsNumberValid(string number)
{
//Whatever code you use to check your number
}
这篇关于打开文本文件,遍历内容并检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!