MolC MolC - 3 months ago 8
C# Question

Avoid writing of equal existing line to text document

I’m new with C# need your help

In this code, I write a some word or phrase to text document with cycle loop. My question is how to avoid writing of equal line, which is already exist in text document and find it in text document, show on output?

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

namespace program_1
{
class Program
{
static void Main(string[] args)
{

int i = 0;

for (;;)
{

Console.Write("Write phrase: ");
var row = Console.ReadLine();

Console.WriteLine(i++ + ". " + (row));

TextWriter tsw = new StreamWriter("lines.txt", true);

tsw.WriteLine(row);

tsw.Close();

}

Console.Read();
}
}
}

Answer

If you want to avoid writing duplicate lines in your file, you need a different approach. First, you need to have all of your lines in memory, then check if the user inputs a line already in memory, then write everything at the end of the program

class Program
{
    static void Main(string[] args)
    {

        int i = 0;
        List<string> wordsTyped = new List<string>();

        // If the file already exists then you can load its content 
        // in memory to start your checks against the current content
        // of the file....
        if(File.Exists("lines.txt"))
            wordsTyped.AddRange(File.ReadAllLines("lines.txt"));

        for (;;)
        {

            Console.Write("Write phrase: (type 'exit' to end)");
            string row = Console.ReadLine();

            // Provide a way to exit from this infinite loop
            if(row == "exit")
                break;

            Console.WriteLine(i++ + ". " + (row));

            // Use IndexOf to find if there is a match for your row 
            // and in which position in the List<string>
            int position = wordsTyped.IndexOf(row);
            if (position != -1)
                Console.WriteLine($"Already inserted. Found match at line {position+1} , type again");
            else
            {
                wordsTyped.Add(row);

                // It of uttermost importance to enclose the StreamWriter
                // in a using statement to be sure to close and dispose it
                // after the write, otherwise you could lock yourself out
                using(StreamWriter sw = File.AppendText("lines.txt"))
                  sw.WriteLine(row);
            }
        }
        // File.WriteAllLines("lines.txt", wordsTyped.ToArray());
        Console.Read();
    }
}
Comments