简体   繁体   中英

How to get specific data from text file

A part of my program has the user save their record within a text document along with their name. The way the program works is that if the user submits their own name, their previous record would be brought back and reinserted into the game. For example, if my name was Justin, I would enter "Justin" into the textbox and the program looks through the textfile, and if it finds someone named Justin, then it would look at the next three lines of data and assign those lines to playerwins, computerwins, and ties respectively. However, any examples I could find either dealt with adding those specific numbers up. I was hoping someone here could point me in the right direction with how I am supposed to structure this code.

private void FileReader(string playername, int playerwins, int computerwins, int ties)
        {
            StreamReader outputfile;
            outputfile = File.OpenText("Records.txt");
            while (!outputfile.EndOfStream)
            {
                if (string.Compare(playername, outputfile.ReadLine()) == 0)
                {
                   //ReadLine() and variable assigning code goes here
                }
            }
        }

If the text file is small enough (and most of them are), I prefer to read and write all of the file's lines at once, rather than one at a time. This separates "file handling" from "score updating", rather than having them intertwined. Resources are also cleaned up automatically (with StreamReader, you have to remember to use 'using' or 'Dispose()' to ensure that resources like file handles are properly released after an error occurs).

For the code below, if playername is already in the file, then playername's scores are updated. Otherwise, playername and playername's scores are added to the end of the file. If the file does not already exist, a new file is created.

The last suggestion would be to rename the method, to something like UpdateOrInsertPlayerScores().

    private void FileReader(string playername, int playerwins, int computerwins, int ties)
    {
        string filename = "Records.txt";
        string[] lines;

        // read entire text file (if any) into lines
        if (File.Exists(filename))
        {
            lines = File.ReadAllLines(filename);
        }
        else
        {
            lines = new string[0];
        }

        // find playername's line (or -1 if not present)
        int p = -1;
        for (int i = 0; i < lines.Length; ++i)
        {
            if (lines[i] == playername)
            {
                p = i;
                break;
            }
        }
        // update (or insert) playername's scores in lines[]
        if (p == -1)
        {
            // playername does not have scores yet; append 4 new lines representing playername's scores
            List<string> newLines = new List<string>();     // copy lines[] to a List<> so we can add new lines to it
            newLines.AddRange(lines);
            newLines.Add(playername);
            newLines.Add(playerwins.ToString());
            newLines.Add(computerwins.ToString());
            newLines.Add(ties.ToString());
            lines = newLines.ToArray();                     // copy expanded List<> back to lines[]
        }
        else
        {
            // update the 3 lines after playername's line with playername's updated scores

            // verify that the 3 lines to be updated are present after the playername's line P
            if ((p + 3) > (lines.Length - 1))
            {
                throw new Exception("Player scores file is not in the expected format.");
            }
            // update the 3 lines in place
            lines[p + 1] = playerwins.ToString();
            lines[p + 2] = computerwins.ToString();
            lines[p + 3] = ties.ToString();
        }

        // re-write entire text file (with updated lines)
        File.WriteAllLines(filename, lines);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM