编辑实际上并没有使用.txt文件作为存储有价值数据的首选方法。这个问题的重点是写到.txt文件的特定部分的
我正在使用一个.txt文件作为一个虚拟数据库来测试一个程序,我遇到了重写某些数据的问题。
例如,.txt文件是这样的:
Ben,welcome1,1
Frank,frankpassword,1
etc...我使用一种简单的方法检索用户信息:
public void ReadUserFile(User_Model UModel)
{
importFile = File.ReadAllText(fileName).Split('\n');
foreach (string line in importFile)
{
data = line.Split(',');
userName = data[0];
password = data[1];
accessLevel = Convert.ToInt32(data[2]);
if (userName == UModel.UserName && password == UModel.UserPassword)
{
UModel.AccessLevel = accessLevel;
if (UModel.UserPassword == "welcome1")
{
UModel.UserPassword = "change password";
break;
}
break;
}
else { UModel.UserPassword = "invalid"; }
lineCount++;
}
}然后,我开始编写一个方法来重写密码,如果密码被存储为‘迎宾1’,但当涉及到它时,我不知道该如何做,或者它是否可以完成呢?
例如:
UModel.UserName = "Ben";
UModel.UserPassword = "welcome1";
UModel.ConfirmPassword = "newpassword";
public void UpdateUserFile(User_Model UModel)
{
importFile = File.ReadAllText(fileName).Split('\n');
foreach (string line in importFile)
{
data = line.Split(',');
userName = data[0]; // "Ben"
password = data[1]; // "welcome1"
if (data[0] == UModel.UserName && UModel.UserPassword == data[1])
{
// Re-write "Ben,welcome1,1" to "Ben,newpassword,1"
}
}
}发布于 2014-03-31 04:28:05
根据文本文件的大小,至少有两个选项:
从一个文件中逐行读取,将其逐行写入另一个临时文件,直到找到匹配的行,然后将修改后的行写入新文件,然后继续从第一个文件中写入所有剩余的行。最后,您需要删除旧文件并将新文件重命名为旧文件。
发布于 2014-03-31 04:26:45
如果它是一个虚拟测试DB,性能不是问题,那么最简单的方法就是读取所有行,根据需要修改它们,然后从头开始重写整个文件。它将比在本质上是线性文件格式的就地编辑要容易得多。
如果您真的想就地编辑文件,请阅读使用StreamWriter类将文件作为FileStream打开,跳转到所需的位置,并向其写入一行。这可能需要使用附带的StreamReader读取原始文件,以便您知道要替换的行的确切文件位置。
发布于 2014-03-31 04:53:55
这是一个简单的程序,以更新密码根据您的用户名。
static void Main(string[] args)
{
string[] a = File.ReadAllLines(@"C:/imp.txt");// to read all lines
Console.WriteLine("enter a name whose password u want to change");
string g=Console.ReadLine();
Console.WriteLine("enter new password");
string j = Console.ReadLine();
for(int i=0;i<a.Length;i++)
{
string[] h = a[i].Split(',');
if(h[0]==g)
{
a[i] = h[0] + ","+j+"," + h[2];
break;// after finding a specific name,you dont need to search more
}
}
File.WriteAllLines(@"C:/imp.txt",a);//to write all data from " a " into file
}https://stackoverflow.com/questions/22753562
复制相似问题