如何将新的唯一字符串添加到文本文件中

本文关键字:添加 文本 文件 字符串 唯一 | 更新日期: 2023-09-27 18:21:51

我有一个文本文件,其中包含几行单词,例如这个

cards
door
lounge
dog
window

我想在列表中添加一个新词,条件是它不存在于列表中。例如,我想添加windcar

我使用File.ReadAllText(@"C:'Temp.txt").Contains(word)但问题是window包含windcards包含car

有什么方法可以对其进行独特的比较吗?

如何将新的唯一字符串添加到文本文件中

如果你没有一个巨大的文件,你可以把它读到内存中,并像任何数组一样处理它:

var lines = File.ReadAllLines(@"C:'Temp.txt");
if(lines.Any(x=>x == word)
{
    //There is a word in the file
}
else
{
    //Thee is no word in the file
}

使用File.ReadLine()并使用String.equals()进行检查,不要查找子字符串。类似这样的东西:

while(!reader.EndOfFile0
{
      if(String.Compare(reader.ReadLine(),inputString, true) == 0)
      {
            //do your stuf here
      }
}

您应该通过Regex匹配来匹配一个精确的工作,我在下面将其作为不区分大小写的。

using ConsoleApplication3;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public static class Program
{
    private static void Main(string[] args)
    {
        // Read the file and display it line by line.
        System.IO.StreamReader file =
           new System.IO.StreamReader("c:''temp''test.txt");
        var line = string.Empty;
        string fileData = file.ReadToEnd();
        file.Close();
        fileData = "newword".InsertSkip(fileData);
        StreamWriter fileWrite = new StreamWriter(@"C:'temp'test.txt", false);
        fileWrite.Write(fileData);
        fileWrite.Flush();
        fileWrite.Close();
    }
    public static string InsertSkip(this string word, string data)
    {
        var regMatch = @"'b(" + word + @")'b";
        Match result = Regex.Match(data, regMatch, RegexOptions.Singleline | RegexOptions.IgnoreCase);
        if (result == null || result.Length == 0)
        {
            data += Environment.NewLine + word;
        }
        return data;
    }
}

尽管我正在读取整个文件并写回整个文件。您可以通过只写一个单词而不是整个文件来提高性能

您可以执行类似的操作

string newWord = "your new word";
string textFile = System.IO.File.ReadAllText("text file full path");
if (!textFile.Contains(newWord))
{ 
    textFile = textFile + newWord;
    System.IO.File.WriteAllText("text file full path",textFile);
}