目前有以下代码:
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);
}
}
}
文本文件的设置为:'username''password
我正在尝试做的是能够编辑密码并使用我的代码将其替换为新密码,但我的代码似乎什么都不做,文本文件保持不变。
答案 0 :(得分:4)
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 :(得分:1)
更正后的代码:
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);
答案 2 :(得分:0)
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);