在添加新行之前检查文件是否包含密钥的最佳方法是什么?

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

我有一个包含以下各列的CSV文件-

键,值

第一行

第二行]

第三行]

我想使用C#在文件中不存在密钥的情况下,向该文件添加新的密钥值?最好的方法是什么?我是否必须逐行遍历并检查键,还是有其他更好的方法?

我没有使用CSVHelper程序包或任何其他CSV编写器。

我有一个包含以下各列的CSV文件-键,值第一,行第二,行第三,行我要向此文件添加新的键值,原因是使用...

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

您可以这样做:

string path = @"PathToFile.csv";
string Content = string.Empty;

using (StreamReader reader = new StreamReader(path))
{
    Content = reader.ReadToEnd();
    reader.Close();
}

if (!Content.Contains("YourKey"))
{
    using (StreamWriter sw = new StreamWriter(path))
    {
        sw.WriteLine(Content + "\nYourkey,YourValue");
        sw.Close();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.