CSV更新/修改

时间:2019-05-13 05:50:49

标签: c#

尝试覆盖以下CSV的单个记录:

PRODUCT,RECORD,ACCOUNT
100,200,300

使用此代码:

public static void UpdateCSV(string filePath, string stringToReplace, string updatedString)
    {
        string path = filePath;
        List<string> lines = new List<string>();

        if (File.Exists(path)) 
        {
            using (StreamReader reader = new StreamReader(path))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Contains(","))
                    {
                        string[] split = line.Split(',');

                        if (split[1].Contains(stringToReplace))
                        {
                            split[1] = updatedString;
                            line = string.Join(",", split);
                        }
                    }

                    lines.Add(line);
                }
            }

            using (StreamWriter writer = new StreamWriter(path, false))
            {
                foreach (string line in lines)
                    writer.WriteLine(line);
            }
        }
    }

但是调用以下内容并没有什么不同(“ PRODUCT”不会更改为“ MYPRODUCT”):

UpdateCSV(@"C:\Test.csv", "PRODUCT", "MYPRODUCT");

这是怎么了? 谢谢。

0 个答案:

没有答案