Open text file, loop through contents and check against

后端 未结 5 2216
清酒与你
清酒与你 2020-12-21 17:24

So I have a generic number check that I am trying to implement:

    public static bool isNumberValid(string Number)
    {
    }

And I want to

相关标签:
5条回答
  • 2020-12-21 17:42

    First, load all lines of the input file in a string array,
    then open the output file and loop over the array of strings,

    Split each line at the space separator and pass every part to your static method.

    The static method use Int32.TryParse to determine if you have a valid integer or not without throwing an exception if the input text is not a valid Int32 number.

    Based on the result of the method write to the output file the desidered text.

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

    Of course this works only if your definition of 'number' is equal to the allowed values for a Int32 datatype

    0 讨论(0)
  • 2020-12-21 17:52

    You could try something like this:

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

    Then print the list using FileStream.

    As other people have mentioned, your isNumberValid method could make use of the Int32.TryParse method, but since you said your text file only contains numbers this may not be necessary. If you're just trying to match the number exactly, you can use number == line.

    0 讨论(0)
  • 2020-12-21 17:53

    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
    }
    
    0 讨论(0)
  • 2020-12-21 18:04

    You don't need to read the entire file into memory all at once. You can write:

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

    The primary advantage here is a much smaller memory footprint, as it only loads a small part of the file at a time.

    0 讨论(0)
  • 2020-12-21 18:06

    You need to replace your loop to look like this:

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

    This would read each line of file, assuming that there is only one number per line, and lines are separated with CRLF symbols. And parse each number to integer, assuming that integer is not greater than 2,147,483,647 and not less than -2,147,483,648, and integers are stored in your locale settings, with or without group separators.

    In case if any line is empty, or contains non-integer - code will throw an exception.

    0 讨论(0)
提交回复
热议问题