如果数组元素在文本文件中不存在,在文件中追加该元素



我在c#中有一个windows窗体应用程序,它包含一个字符串数组(string[]),其中包含几个元素和一个逐行存储文本的文件。现在我想循环遍历数组,看看数组元素是否已经存在于文件中,如果不存在,就把数组元素写到文件的末尾。但是,我无法得到正确的逻辑

File.AppendAllLines(filePath,stringArray.Except(File.ReadLines(filePath)));

try this:

string [] array ={"a","b","c","d","e","f","g"};
string [] fromfile =File.ReadAllLines("file.txt");
List<string>toadd = new List<string>();
foreach(string s in array){
    bool found =false;
    foreach(string fs in fromfile){
        if(fs==s){
         found =true;
            break;
        }
        if(found){
            toadd.Add(s);
        }
    }
}
File.AppendAllLines("file.txt",toadd);

PS:别忘了:

using System.IO;//for the file
using System.Collections.Generic; // for the list (toadd)

最新更新