在C#的文本文件中创建无重复字符串条目的列表

时间:2016-11-30 14:11:45

标签: c# linq io

我是C#编程的初学者。 我想在C#Console中为桌面创建一个文本文件,希望将我输入的新字符串值添加到创建的文本文件的新行中。 这是我的工作:

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

我通过控制台创建了该文件,但我希望每个输入的字符串都是唯一的,我在google上查了一下,但我很困惑。我希望控制台告诉我新输入是否已经存在,如果是,则警告我“它已经存在!输入另一个字:”,如果它不存在,只需将其添加到列表中即可。我需要你的帮助。

谢谢大家的关注。在Mr.Ankitkumar Bhatt的帮助下,这是我最近的工作:

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

但是我想指出,我希望程序识别列表中的所有项目,通过我的上一个方法,它确实有效,但是当我关闭,再次打开程序时,它不会给我警告New Word已存在,不会将其添加到文件中。我该怎么做呢?

4 个答案:

答案 0 :(得分:4)

如果“没有重复”,请查看HashSet<String>;您可能会发现TextWriterTextReader过于复杂 - 请尝试File.ReadLines()File.AppendAllLines

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

如果您想要一个接一个地添加几个字词(将空行退出):

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

答案 1 :(得分:2)

在注入单词检查之前,单词是否存在

string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\list.txt");

if (!FileContents.Contains(newWord))
{  
    // Add to file // 
}

答案 2 :(得分:1)

1)读取文件并将其内容写入string[](字符串数组):

var lines = File.ReadAllLines(wlist , Encoding.UTF8);

2)阅读您的输入并检查重复项:

var input = Console.ReadLine();

if (lines.Contains(input)) {
    //Warning message
} else {
    //Success message    
}

答案 3 :(得分:1)

这可以通过多种方式实现。我将提出一个最接近您的代码的解决方案。绝对有一种更优雅的方式来实现这一目标,但这是一种快速而肮脏的方法来实现这一目标。

一种方法是从文本文件中进行foreach检查,以便:

var isWordPresent = false;
var textLines = File.ReadAllLines(wlist);
foreach (var line in textLines) {
    if (line.contains(newWord) {
        isWordPresent = true;
    }
}
if (isWordPresent == false) {
    inject.WriteLine(newWord);
    inject.Close();
    isWordPresent = false; //added this portion incase you run this code in a while loop 
//so you can reuse it. You would need to have the boolean reset to false
}