简体   繁体   中英

How do I overwrite a text file line by line using StreamWriter WriteLine in c#

As part of my c# learning, I have a simple game on a console application. I have now added a text file to record the top score. It has 4 lines, date, number of attempts, time in minutes and additional time in seconds. The text file is part of the project solution, and although I don't specify the full path, I can read the file with StreamReader and output the lines without any trouble. But if I have a new top score, and I wish to overwrite the values in the text file, nothing is happening. The text file remains unmodified.

I have tried using StreamWriter. It feels somewhat intuitive to use StreamReader ReadLine to bring the data into the application and StreamReader WriteLine to output. But the output piece is not working. For my sins, this is my code. There are some similar queries on stackooerflow, but I've not found a solution that appears to fit my query.

if (newBestScore== true)
{
    DateTime dateToday = DateTime.Now;
    string dateString=dateToday.ToShortDateString();
    string currAttempts=CurrentAttempts.ToString();
    using (StreamWriter newTopScore = new StreamWriter("TopScore.txt"))
    {
        newTopScore.WriteLine(dateString);
        newTopScore.WriteLine(currAttempts);
        newTopScore.WriteLine(timeTaken.Minutes);
        newTopScore.WriteLine(timeTaken.Seconds);
        newTopScore.Close();
    }
}

I'll not fix your problem, but I'll tell you how you can fix all problems of this sort by yourself in the future.

Download Process Monitor and add a filter for your application, like so:

Process Name , contains , <myapp>.exe then Include and then add this filter by pressing the Add button.

进程监控

Then start recording and look for TopScore.txt and see in which directory it looks for that file. You can use the find dialog for that ( Ctrl + F ):

查找进程监视器的对话框

Then have a look at the full file name of that file, so you know where it it being written. You can even right click and choose "Jump to...".

Understand what a working directory is. The file will be written in the working directory if you didn't provide a full path.

Why go this way? This way proves that you have a problem independently. You don't change the source code. Whenever you change the source code and eg add diagnostics code like Console.WriteLine(Path.GetFullPath(...)); , problems may disappear.

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