检查字符串是否在文件中,如果是,则替换包含字符串的特定行

时间:2018-11-29 13:41:26

标签: c#

Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
int classicscore = 0;
string path = "";
File.AppendAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));

因此从本质上讲,这将在文件的每一行中依次写上名称和分数,我想添加某种形式的验证,以检查是否有人输入的用户名在文件中,然后将新行覆盖整个行用户名和分数数据。

“ classicsscore”引用用户的分数,该分数以前存储为整数。然后将其与该人的输入字符串用户名即“ John 12”一起放入文本文件中。我想要的是,如果一个人输入John作为其用户名(分数为400),那么该行将被替换为“ John 400”,而不会影响文本文件的其余部分。

我正在使用Visual Studio,C#控制台程序。

很抱歉,如果这是重复的话,我自己找不到特定答案。

1 个答案:

答案 0 :(得分:1)

我认为这样的事情应该对您有用。

public void AddOrUpdate(string userName, int score)
{
    string path = "";
    var newLine = userName + " " + score;
    var lines = File.ReadAllLines(path);
    var wasUpdated = false;
    using (var writer = new StreamWriter(path))
    {
        foreach (var line in lines)
        {
            var foundUserName = line.Substring(0, line.LastIndexOf(' '));
            if (foundUserName == userName)
            {
                writer.WriteLine(newLine);
                wasUpdated = true;
            }
            else
                writer.WriteLine(line);
        }
        if(!wasUpdated)
            writer.WriteLine(newLine);
    }
}

但是除非您出于某种原因需要这种特定格式,否则使用数据库将是更好的选择。

相关问题