[英]How to add a new unique string to text file
我有一個文本文件,其中包含幾行單詞,例如這樣
cards
door
lounge
dog
window
我想在該列表中添加一個新單詞,但條件是該列表中尚不存在該單詞。 例如我想增加wind
或car
我使用File.ReadAllText(@"C:\\Temp.txt").Contains(word)
但問題是window
有wind
而cards
有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
}
}
您應該進行正則表達式匹配,以便匹配確切的作品,下面我將其設為不區分大小寫。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.