C#替换CSV文件中每行的值

问题描述 投票:0回答:1

我试图用“现有值”+“a”替换.csv文件中的值。换句话说,我想在所有行,一个特定列附加“a”,但省略标题行。我的代码在文件的底行成功,但我相信我的foreach循环相对于while循环的位置导致了问题。有什么东西明显我错过了吗?如果是这样,我道歉,因为我是初学者。请注意,我知道有一些冗余的代码,我正在清理一次工作。谢谢。

public static void ReadReplace()
{
    using (StreamReader sr = new StreamReader(@"C:\TestDirectory\Test.csv"))
    {
        foreach(string test in File.ReadLines(@"C:\TestDirectory\Test.csv"))
        {
            String line;

            while ((line = sr.ReadLine()) != null)
            {
                string[] parts = line.Split(',');
                string serviceId = parts[34].Trim('"');
                string appendedServiceId = serviceId + "a";

                string text = File.ReadAllText(@"C:\TestDirectory\Test.csv");
                text = text.Replace(serviceId, appendedServiceId);
                File.WriteAllText(@"C:\TestDirectory\TestUpdated.csv", text);

            }
        }
    }

}
c# csv streamreader
1个回答
0
投票

您正在重新读取源文件,并在每次循环迭代时重写一次。

尽管此处存在所有其他问题,但请将最终的写入调用移出循环。你仍然无缘无故地阅读这个文件两次,但我会把它留给你。

我还删除了你不需要和未使用的“测试”循环。

未经测试:

public static void ReadReplace()
{

    string text = File.ReadAllText(@"C:\TestDirectory\Test.csv");

    using (StreamReader sr = new StreamReader(@"C:\TestDirectory\Test.csv"))
    {
        String line;    
        while ((line = sr.ReadLine()) != null)
        {
            string[] parts = line.Split(',');
            string serviceId = parts[34].Trim('"');
            string appendedServiceId = serviceId + "a";

            text = text.Replace(serviceId, appendedServiceId);

        }
    }

    File.WriteAllText(@"C:\TestDirectory\TestUpdated.csv", text);

}
© www.soinside.com 2019 - 2024. All rights reserved.