Open text file, loop through contents and check ag

2019-01-28 23:35发布

问题:

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

    public static bool isNumberValid(string Number)
    {
    }

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

etc.

The new textfile I want to write would just be the numbers with true or false appended to the end:

4564 true

回答1:

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
}


回答2:

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.



回答3:

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.



回答4:

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.



回答5:

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