C# 打开文本文件,循环浏览内容并对照

C# 打开文本文件,循环浏览内容并对照,c#,io,openfiledialog,C#,Io,Openfiledialog,因此,我有一个我正在尝试实现的通用数字检查: public static bool isNumberValid(string Number) { } 我想读取文本文件的内容(仅包含数字),检查每一行的数字,并使用isNumberValid验证它是否为有效数字。然后我想将结果输出到一个新的文本文件,我已经做到了: private void button2_Click(object sender, EventArgs e) { int siz

因此,我有一个我正在尝试实现的通用数字检查:

    public static bool isNumberValid(string Number)
    {
    }
我想读取文本文件的内容(仅包含数字),检查每一行的数字,并使用
isNumberValid
验证它是否为有效数字。然后我想将结果输出到一个新的文本文件,我已经做到了:

    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)
            {
            }
        }
    }
如果有人能帮上忙的话,我会被困在这里的

文本文件在列表中包含多个数字:

4564

4565

4455

等等

我想写的新文本文件就是结尾附加了true或false的数字:

4564对


您需要将循环替换为如下所示:

string[] lines = File.ReadAllLines(file);
foreach (var s in lines)
{
  int number = int.Parse(s);
  ...
}
这将读取文件的每一行,假设每一行只有一个数字, 和线用CRLF符号分隔。并将每个数字解析为整数,假设整数不大于2147483647且不小于-2147483648,并且整数存储在您的区域设置中,带或不带组分隔符


如果任何一行为空或包含非整数,则代码将抛出异常。

首先,将输入文件的所有行加载到字符串数组中,
然后打开输出文件并在字符串数组上循环

在空间分隔符处拆分每一行,并将每一部分传递给静态方法

静态方法用于确定是否具有有效整数,如果输入文本不是有效的Int32数字,则不会引发异常

根据方法的结果,将所需文本写入输出文件

// Read all lines in memory (Could be optimized, but for this example let's go with a small file)
string[] lines = File.ReadAllLines(file);
// Open the output file
using (StringWriter writer = new StringWriter(outputFile))
{
    // Loop on every line loaded from the input file
    // Example "1234 ABCD 456 ZZZZ 98989"
    foreach (string line in lines)
    {
        // Split the current line in the wannabe numbers
        string[] numParts = line.Split(' ');

        // Loop on every part and pass to the validation
        foreach(string number in numParts)
        {
            // Write the result to the output file
            if(isNumberValid(number))
               writer.WriteLine(number + " True");
            else
               writer.WriteLine(number + " False");
        }
    }
}

// Receives a string and test if it is a Int32 number
public static bool isNumberValid(string Number)
{
    int result;
    return Int32.TryParse(Number, out result);
}

当然,只有当“number”的定义等于Int32数据类型的允许值时,这才有效。您可以尝试以下方法:

FileStream fsIn = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
using (StreamReader sr = new StreamReader(fsIn))
 {

     line = sr.ReadLine();

     while (!String.IsNullOrEmpty(line)
     {
        line = sr.ReadLine();
       //call isNumberValid on each line, store results to list
     }
 }
然后使用
FileStream
打印列表


正如其他人所提到的,您的
isNumberValid
方法可以使用
Int32.TryParse
方法,但是由于您说您的文本文件只包含数字,因此可能没有必要这样做。如果您只是想精确匹配数字,可以使用
number==line

不需要一次将整个文件读入内存。你可以写:

using (var writer = new StreamWriter(outputPath))
{
    foreach (var line in File.ReadLines(filename)
    {
        foreach (var num in line.Split(','))
        {
            writer.Write(num + " ");
            writer.WriteLine(IsNumberValid(num));
        }
    }
}

这里的主要优点是内存占用小得多,因为它一次只加载文件的一小部分。

您可以尝试这样做,以保持最初遵循的模式

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
}

数字之间有某种分隔吗?输入文件中的一行是如何格式化的?您希望写入新文件的结果是什么?true或false,文本文件只是一个数字列表,每行的数字数量相同。将更新答案。它调用isNumberValid来检查困扰我的文本文件中的数字。这不检查isNumberValid tho?例如,如果我想循环遍历文本文件中的每一行并检查数字是否有效,您的方法不会这样做吗?我试图检查文本文件中的每一行是否都是isValidNumber中的有效数字之一,如果是,则将“true”或“false”附加到一个新的文本文件(带有相应的数字).检查您是否有数字的关键是因为我假设您的行中有一些不能是数字的内容,如
1234 ABCD 456 ZZZZ 98989
。我的答案是一行,将行分割成单独的“单词”,并将每个单词传递给iNumberValid进行检查。对不起,Steve,我只是不想发布我的数字验证代码,我正在验证这些数字是否代表有效引用。例如,它可能像一个串行键,如果它不匹配,那么我需要它在一个新的文本文件中输出false。那么,问题出在哪里?只需删除IsValidNumber中的代码并使用您自己的代码。调用前后的代码与验证传入字符串的方式无关。这只是两个带字符串拆分的循环。或者您只是想在一个点上验证整行代码?