2016-11-30 11 views
3

私はC#プログラミングの初心者です。 C#Consoleのデスクトップにテキストファイルを作成したかったので、作成したテキストファイルの新しい行に入力した新しい文字列値を追加します。 は、これが私の仕事です:私はコンソールを介してファイルを作成しC#のテキストファイルに重複しない文字列エントリのリストを作成する

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)[email protected]"\list.txt"; 
     FileStream create = File.Open(wlist, FileMode.Create); 
     create.Close(); 
     for (int i = 0; i < 100; i++) 
     { 
      Console.WriteLine("New Word"[email protected]" ("+(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(); 
      } 
     } 
    } 

しかし、私はそれを指すようにしたい、私はプログラムが私の最後の方法により、リスト内の項目のすべてを認識したい、それは非常に動作しますしかし、私がプログラムを閉じてもう一度開くと、新しい単語がすでに存在しているという警告は表示されず、ファイルには追加されません。どうすれば残りのことができますか?

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

2)読む:

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

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

最初に単語をリストに追加します。その単語のリストを確認してください。リストに存在しない場合はファイルに書き込み、それ以外の場合はユーザに通知してください – bixarrio

+0

読み取りと書き込みの2つのIO操作を同時に行う必要があります。したがって、 'TextReader' **と** TextWriterを使用してください。 – HimBromBeere

+0

[HashSet](https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx)を参照してください。 'Add'メソッドは、重複しているかどうかにかかわらずtrueまたはfalseを返します。 @ bixarrio。 –

答えて

4

てください、HashSet<String>を見ています。あなたはTextWriterTextReaderがあまりにも複雑であるかもしれない - 代わりにFile.AppendAllLinesFile.ReadLines()を試してみてください。

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

あなたはいくつかの言葉、1の後に1(出口へ空行を置く)を追加したい場合:

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

です^^ ..あなたは注文するものを自分で知る前に正しい飲み物を提供しているバーテンダーのようなものです;)ニース、彼の質問への過度の答え:p – TripleEEE

+0

ありがとうございました!!! :) –

2

単語は単語をチェック注入する前に存在しているかどうかが好きあなたの入力と重複のチェック:

var input = Console.ReadLine(); 

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

これは私が行くだろうより多くの鉱石です - 多分ファイルが非常に大きい場合、私はむしろ、 'foreach(File.ReadLines(" Filename ")のvar行)のようなものを使用したいと思います。 – TripleEEE

1

1)は、文字列のstring[](配列)にその内容をファイルの読み取りと書き込みの下に

+0

を短縮することができるので、完全なファイルをメモリから読み取ることができます。 { line.Contains(newWord) }もしあなたが自分のような気があるなら 'if(lines.Contains(input))'。 –

+0

@JayGouldご意見ありがとうございます。あなたが正しい。私は答えを編集しました – rbr94

+0

'.ToList();'は 'File.ReadAllLines'が配列を返し、配列自身の' Contains() 'メソッドを使うことができるので* redundant *です –

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 
} 
関連する問題