Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c# - Open text file, loop through contents and check against

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...