简体   繁体   中英

How to add a new unique string to text file

I have a text file contains several lines with words, for example like this

cards
door
lounge
dog
window

I want to add a new word into that list with the condition that it does not already exist in the list. For example I want to add wind or car

I use File.ReadAllText(@"C:\\Temp.txt").Contains(word) But the problem is window contains wind and cards contain car

Is there any way to compare it uniquely?

If you have not a huge file, you can read it to memory and process it like any array:

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
}

Use File.ReadLine() and check for with String.equals(), dont look for substrings. Something Like this:

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

You should do through Regex match so that you are matching an exact work, and I have made this below as case insensitive.

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;
    }
}

Although I am reading an entire file and writing an entire file back. You can improve the performance by only writing one word rather a whole file again.

you can do something like

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM