问题描述
我能够编辑每个字段,但是这仅适用于CSV文件的第一行。如果我尝试输入第二行或第三行等上的患者ID,它将不会编辑任何数据。有人知道为什么吗?
我将这些行存储在一个字符串中,然后将它们分成另一个字符串中的不同字段,使用了for循环,我认为该循环将遍历每行直到找到ID。
{
bool edited = false;
string ID,change;
int choice;
Console.WriteLine("Please enter the ID of the customer you would like to Update: ");
ID = (Console.ReadLine());
Console.WriteLine("\n");
Console.WriteLine("Which field would you like to update? ");
Console.WriteLine("1: Patient ID: ");
Console.WriteLine("2: Patient Name: ");
Console.WriteLine("3: Patient age: ");
Console.WriteLine("4: Patient gender: ");
Console.WriteLine("5: Patient address: ");
Console.WriteLine("6: Patient Phone Number: ");
choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("New data: ");
change = (Console.ReadLine());
string[] lines = System.IO.File.ReadAllLines("patinfo.csv");
StreamWriter Write = new System.IO.StreamWriter("temp.csv");
for (int i = 0; i < lines.Length; i++) // will read each line in the file.
{
string[] fields = lines[i].Split(','); // this here is splitting up each field,so ID,Name,Age will have their own index value
if (fields[i] == ID) // this is where you will make the change,we need to determine the field here
{
for (int k = 0; k <= fields.Length; k++)
{
if(k == choice)
{
fields[k-1] = change;
Write.WriteLine(fields[0] + "," + fields[1] + "," + fields[2] + "," + fields[3] + "," + fields[4] + "," + fields[5]); // change is made
}
}
}
else
{
if (!edited)
{
Write.WriteLine(fields[0] + "," + fields[2]+ "," + fields[5]); // if not edited then it will print the line to the temp file
}
}
}
Write.Close();
File.Delete("patinfo.csv");
System.IO.File.Move("temp.csv","patinfo.csv");
Console.ReadLine();
解决方法
if (fields[0] == ID) // replaced i with 0
{
for (int k = 1; k <= fields.Length; k++) // replaced 0 with 1
提示:如果未在[1,6]中未写入行,请选中“更改”