我有我在.txt文件中阅读的代码。文本文件包含名字和姓氏的值以及数字。
"丹尼尔" "默罗" " 1234"
我正在尝试使用StreamWriter编辑特定值。但是,我现在的代码编辑整个.txt文件并替换所有内容。我只想替换我的数字值。
static classMates[] readClassMates(classMates[] classMateInfo)
{
StreamReader sr = new StreamReader(@"C:\Users\Callum\Documents\class.txt");
int count = 0;
while (!sr.EndOfStream)
{
classMateInfo[count].first = sr.ReadLine();
classMateInfo[count].last = sr.ReadLine();
string idTemp = sr.ReadLine();
classMateInfo[count].ID = Convert.ToInt32(idTemp);
count++;
}
sr.Close();
return classMateInfo;
static void editClassMates(classMates[] classMateInfo)
{
Console.Write("Who's number would you like to change? ");
string classMateInput = Console.ReadLine();
for (int i = 0; i < classMateInfo.Length; i++)
{
if (classMateInfo[i].last.Equals(classMateInput))
{
Console.Write("Enter new number: ");
string temp = Console.ReadLine();
int classMateNumber = Convert.ToInt32(temp);
StreamWriter sw = new StreamWriter(@"C:\Users\Callum\Documents\class.txt");
for (int j = 0; j < classMateInfo.Length; j++)
{
sw.WriteLine(classMateNumber);
}
sw.Close();
}
}
}
所以我的问题是,如何编辑.txt文件中的特定值?我已经尽了最大努力,但我已经坚持了很久!
答案 0 :(得分:5)
如果文件不是很大(因此内存使用不是问题),那么:
var text = File.ReadAllText(@"C:\Users\Callum\Documents\class.txt");
var updatedText = text.Replace(...); // Do your string replacement here
File.WriteAllText(@"C:\Users\Callum\Documents\class.txt");