简体   繁体   中英

Simple issue Writing from array to text file after storing what I have read as array and editing one of the arrays

Simple issue with writing back from array to text file after storing what I have read as array and editing one of the arrays. I need to write all the information back from the array into the text file.

I have read all the text and they are stored as variable[] called scores.

I want to write this back with new scores for one of the players

I have the players name in a text box on my form

My text file consists of playername, lowscore highscore, blank space line inbetween Then three more players in this format.

                        scores = File.ReadAllLines(Source);
                        int counter = 0;
                        List<Score> Results = new List<Score>();

                        while (counter < scores.Length)
                        {
                            Score scor = new Score();
                            scor.Name = scores[counter];
                            int.TryParse(scores[counter + 1], out scor.low);
                            int.TryParse(scores[counter + 2], out scor.high);
                            counter += 3;
                        }

                        StreamWriter sw = new StreamWriter(Source);
                        while (m_SelectedItem == Name)
                        {
                         //In here I need help
                        }

If you just want to add some stuff to the end of the text file, use File.AppendAllLines(Source,score); If you want to edit something in the middle of the text file, is there a reason you can't just overwrite the whole file? So after you've edited the scores (I'm assuming the edited scores are all in the Results list?) do something like this:

List<string> NewScores=new List<string>();
foreach(Score score in Results){
    NewScores.Add(score.Name);
    NewScores.Add(score.low);
    NewScores.Add(score.high);
    NewScores.Add("");
}
File.WriteAllLines(Source,NewScores.ToArray());

I'd store data like this in an XML file rather than text. That will allow you to easily sort, edit and query the data, and allow node-based navigation of the data which is what you seem to be trying to do here. I think the C# XML tools are pretty easy to learn.

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