How do I avoid having the file I created in txt write two equal C # files?

1

Well, I'll explain the problem to you: I have a system that reads the barcodes and in this system I need the txt file that is receiving the code do not receive duplicate / duplicate files, ie it can not receive the same code 2 times.

I'm having problems doing this without a database and because the windows platform where this system will run is quite old I having to program in VS2008.

Below is a portion of the code, where the file Count.txt is created by the system and the file receives the barcode and location of the collection:

if (!File.Exists(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\Contagem.txt"))
{
    File.Create(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\Contagem.txt").Close();
}
StreamWriter sw = new StreamWriter(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\Contagem.txt", true);

sw.WriteLine("|" + txtCodBarras.Text + "|" + txtLocal.Text.Substring(txtLocal.Text.Length - 3) + "|");

sw.Close();
sw.Dispose();
    
asked by anonymous 15.03.2018 / 16:06

2 answers

1

If your goal is to avoid duplicating a record you must first read the file and check that it no longer has this record before writing the new one

   string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\Contagem.txt";

    if (!File.Exists(path))
    {
        File.Create(path).Close();
    }


    bool existeRegistro = false;

    using (StreamReader reader = new StreamReader(path))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            if (line.Contains(txtCodBarras.Text))
                existeRegistro = true;

            if (existeRegistro)
                break;
        }
    }

    if (!existeRegistro)
    {

        using (StreamWriter sw = new StreamWriter(path, true))
        {
            sw.WriteLine("|" + txtCodBarras.Text + "|" + txtLocal.Text.Substring(txtLocal.Text.Length - 3) + "|");
        };

    }
    
15.03.2018 / 20:37
2

Leandro Angelo's answer gives you a path that works fine, but has a race condition problem. Do not try to verify that the file exists, try using it if it gives problem handle the error. It is a complicated problem because it will almost always work, especially in tests and will give the impression that it has no problem whatsoever, the day that gives you a problem, you will not have the slightest idea of what happened, or even because you will not be able to reproduce.

A example with path is the same thing.

    
17.03.2018 / 15:27