Ahmet G. Ahmet G. - 9 days ago 6
C# Question

Creating a list of no duplicate string entries in a text file at C#

I'm a beginner at C# programming.
I wanted to create a text file to the desktop in C# Console, which is wanted to add my input new string value to the created text file's new line.
This is my work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace noteonce
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine();
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\list.txt";
TextWriter inject = new StreamWriter(wlist, true);
inject.WriteLine(newWord);
inject.Close();
Console.WriteLine("New word has been added! ");Console.ReadKey();
}
}
}


I created the file through the console, but I want each of my entered string to be unique, I did some look up on google but I'm so confused. I want the console to tell me that whether the new input already exists or not, If it is, to warn me as "It already exists! Input another word : ", If it does not exist, just to add it to the list. I need your assistance.

Thank you all for your attention. By the help of Mr.Ankitkumar Bhatt, This is my recent work :

static void Main(string[] args)
{
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+@"\list.txt";
FileStream create = File.Open(wlist, FileMode.Create);
create.Close();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("New Word"+@" ("+(100-i)+") :");
string newWord = Console.ReadLine();
string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\list.txt");
TextWriter inject = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\list.txt", true);
if (!FileContents.Contains(newWord))
{
inject.WriteLine(newWord);
inject.Close();
}
else
{
Console.WriteLine("It already exists!");
Console.ReadKey();
inject.Close();
}
}
}


But I want to point that, I want the program to recognize all of items in the list, by my last method, it quite works, but when I close, and open the program again, It doesn't give me the warning that New Word is already exist, doesn't add it to the file neither. How can I do the rest ?

Answer

In case of "no duplicate" please, have a look at HashSet<String>; you may find TextWriter and TextReader being too complex - try File.ReadLines(), File.AppendAllLines instead:

   static void Main(string[] args) {
     // better practice is paths combining
     string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
     // unique (no duplicates) strings so far
     HashSet<String> hash = new HashSet<string>(
       File.ReadLines(path), // file to read from
       StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")

     Console.WriteLine("New Word: ");

     string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"

     if (!string.IsNullOrEmpty(newWord)) // let's not add an empty string
       if (!hash.Contains(newWord)) {
         // add new word to the end of file
         File.AppendAllLines(path, new string[] {newWord});

         Console.WriteLine("New word has been added!");
       } 
       else 
         Console.WriteLine("It already exists! Input another word");
     else
       Console.WriteLine("We don't add empty lines."); 

     Console.ReadKey();
   }

In case you want to add several words, one after one (put an empty line to exit):

 static void Main(string[] args) {
   // better practice is paths combining
   string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
   // unique (no duplicates) strings so far
   HashSet<String> hash = new HashSet<string>(
     File.ReadLines(path), // file to read from
     StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")

   while (true) {
     Console.WriteLine("New Word: ");

     string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"

     if (string.IsNullOrEmpty(newWord))
       break;

     if (hash.Add(newWord)) {
       File.AppendAllLines(path, new string[] {newWord});

       Console.WriteLine("New word has been added!");
     }
     else 
       Console.WriteLine("It already exists! Input another word.");
   }

   Console.ReadKey();
 }