【问题标题】:Open text file, loop through contents and check against打开文本文件,循环浏览内容并检查
【发布时间】:2013-05-14 19:42:23
【问题描述】:

所以我有一个我正在尝试实施的通用号码检查:

    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

等等

我要写的新文本文件只是末尾附加了真或假的数字:

4564 对

【问题讨论】:

  • 数字之间有某种分隔吗?输入文件中的一行是如何格式化的?
  • 要写入新文件的结果是什么?
  • true or false,文本文件只是一个数字列表,每行都有相同数量的数字。将更新答案。

标签: c# io openfiledialog


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

    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
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        【解决方案4】:

        你可以试试这样的:

        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

        【讨论】:

        • 它调用 isNumberValid 来检查困扰我的文本文件中的数字。
        【解决方案5】:

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

        在空格分隔符处分割每一行并将每一部分传递给您的静态方法。

        静态方法使用Int32.TryParse 来确定您是否有有效的整数,如果输入文本不是有效的 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);
        }
        

        当然,这仅在您对“数字”的定义等于 Int32 数据类型的允许值时才有效

        【讨论】:

        • 这不检查 isNumberValid 吗?例如,如果我想遍历文本文件中的每一行并检查数字是否有效,您的方法不会这样做吗?我正在尝试检查文本文件中的每一行是否是 isValidNumber 中的有效数字之一,然后将“true”或“false”附加到新文本文件(带有相应的数字)。
        • 检查你是否有数字的重点是因为我想你有一些不能像1234 ABCD 456 ZZZZ 98989这样的数字的行。我的答案是一行,将行拆分为单独的“单词”并将每个单词传递给 IsNumberValid 进行检查。
        • 对不起史蒂夫我只是不想发布我的数字验证代码,我正在验证这些数字是否代表有效的参考。例如,它可能像一个序列号,如果它不匹配,那么我需要它在一个新的文本文件中输出 false。
        • 好吧,问题出在哪里?只需删除 IsValidNumber 中的代码并使用您自己的代码。调用前后的代码与验证传入字符串的方式无关。它只是两个带有字符串拆分的循环。
        • 或者您只是想在一处验证整行?
        猜你喜欢
        • 2017-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多