打开文本文件,循环浏览内容并进行检查

时间:2013-05-14 19:42:23

标签: c# io openfiledialog

所以我有一个我想要实现的通用号码检查:

    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 true

5 个答案:

答案 0 :(得分:4)

您无需一次性将整个文件读入内存。你可以写:

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));
        }
    }
}

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

答案 1 :(得分:3)

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

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
}

答案 2 :(得分:0)

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

string[] lines = File.ReadAllLines(file);
foreach (var s in lines)
{
  int number = int.Parse(s);
  ...
}

这将读取每行文件,假设每行只有一个数字, 和行用CRLF符号分隔。并将每个数字解析为整数,假设整数不大于2,147,483,647且不小于-2,147,483,648,并且整数存储在您的语言环境设置中,包含或不包含组分隔符。

如果任何行为空,或者包含非整数 - 代码将引发异常。

答案 3 :(得分:0)

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

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

如果输入文本不是有效的Int32编号,则静态方法使用Int32.TryParse来确定是否有有效整数而不抛出异常。

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

// 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数据类型的允许值时,这才有效

答案 4 :(得分:0)

您可以尝试这样的事情:

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

相关问题