如何解决需要帮助来编辑CSV文件中的字段吗?
我能够编辑每个字段,但是这仅适用于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]中未写入行,请选中“更改”
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。