Question Why does my code Write to lines that aren't specified

idontknowbro

New member
Joined
Dec 2, 2016
Messages
1
Programming Experience
Beginner
I have this code below which is Replace an integer by adding the integer in the file to the integer that the user has input during the console session. It does that fine. However, it seems to increment the other 3 lines, even though the code to do so is not there. Here is my code:

C#:
using (StreamReader StreamReader = new StreamReader(sUsername + ".txt"))                //Open a StreaReader object on the Users file            {
                //Read the whole file
                string ReadFile = File.ReadAllText(sUsername + ".txt");                                      //Read the whole file


                //Find specific line and put it in a string
                string ArtLine = File.ReadLines(sUsername + ".txt").Skip(5).Take(1).First();
                string DanceLine = File.ReadLines(sUsername + ".txt").Skip(7).Take(1).First();                 //Store String that contains the Art score taken from the file
                string MusicLine = File.ReadLines(sUsername + ".txt").Skip(9).Take(1).First();                 //Store String that contains the Art score taken from the file
                string CraftsLine = File.ReadLines(sUsername + ".txt").Skip(11).Take(1).First();                 //Store String that contains the Art score taken from the file


                
                int ArtParsed = Int32.Parse(ArtLine);


                //Add  the stored  file integer to recorded integer
                int iCmbndArt = ArtParsed + iArtAmount;                                            //Add both strings together


                //Convert the combined integers to a string
                string CombinedParsed = iCmbndArt.ToString();
                
                //Replace original with new combined integer
                ReadFile = ReadFile.Replace(ArtLine, CombinedParsed);                                    //Find line containing original string
                StreamReader.Close();


                //Write everything back to the file
                File.WriteAllText(sUsername + ".txt", ReadFile);                                            //Re-Write the file containing the original string using sUsername as both the Path and the Text Source


                iArtAmount = 0;
            }

Here is an image so you can see the specific lines of my text file:
View attachment 275
 

Attachments

  • Untitled.png
    Untitled.png
    10.3 KB · Views: 63
Last edited:
String.Replace Method (String, String) (System)
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It would be better if you read all lines of file, replace the text of a line in the returned array, then write the array to file. (File.ReadAllLines/WriteAllLines)
 

Latest posts

Back
Top Bottom