简体   繁体   中英

using .replace to replace a word in text document (c#)

currently have the following code:

    string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");

    for (int i = 0; i < fileLineString.Length; i++)
    {
        string[] userPasswordPair = fileLineString[i].Split(' ');

        if (Session["user"].ToString() == userPasswordPair[0])
        {
            userPasswordPair[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
        }
    }
}

the text file is set out as: 'username' 'password

what i'm trying to do is be able to edit the password and replace it with a new one using my code, but my code seems to do nothing and the text file just stays the same.

string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");

for (int i = 0; i < fileLineString.Length; i++)
{
    string[] userPasswordPair = fileLineString[i].Split(' ');

    if (Session["user"].ToString() == userPasswordPair[0])
    {
        // set the new password in the same list and save the file
        fileLineString[i] = Session["user"].ToString() + " " + newPasswordTextBox.Text;
        File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt"), fileLineString);
        break; // exit from the for loop
    }
}
  1. At the moment, you're not storing the file.
  2. Your replace is not assigned to a variable (Replace does not edit or write anything, it just returns the new string object).

Corrected code:

string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");

for (int i = 0; i < fileLineString.Length; i++)
{
    string[] userPasswordPair = fileLineString[i].Split(' ');

    if (Session["user"].ToString() == userPasswordPair[0])
    {
        fileLineString[i] = fileLineString[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
        break;
    }
}

File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt", fileLineString);
        String _userName = "User";
        String _newPassword = "Password";
        // Reading All line from file
        String _fileContent = System.IO.File.ReadAllLines("filePath").ToString();
        // Pattern which user password like to changed            
        string _regPettern = String.Format(@"{0} ?(?<pwd>\w+)[\s\S]*?", _userName);
        Regex _regex2 = new Regex(_regPettern, RegexOptions.IgnoreCase);
        String _outPut = Regex.Replace(_fileContent, _regPettern, m => m.Groups[1] + " " + _newPassword);
        // Writing to file file
        System.IO.File.WriteAllText("filePath", _outPut);

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