Record and recover information in files

Asked

Viewed 811 times

1

How do I write data to a file and then recover it?

I have a enrollment system. I start a folder in Windows and within it I generate the enrollments sequentially. I finish and go home and the next day, I will generate new set license plates, but I should start from the last one and add one more: matricula_atual + 1. I need to continue recording on it without losing what already existed.

How I write the file to a folder?

  • Has this resolved? Can you accept any of the answers?

2 answers

3

Test if file exists:

if(File.Exists(@"C:\arquivo.txt"))
    // faça algo

Write multiple lines to a file (overwrite content):

System.IO.File.WriteAllText (@"c:\arquivo.txt", "Matricula");

Read content from the text file:

public static string ObtenhaConteudoDeArquivoTexto(string pathArquivo)
{
     StreamReader streamReader = new StreamReader(pathArquivo);
     string text = streamReader.ReadToEnd();
     streamReader.Close();
     return text;
}

Includes content for a physical file:

File.AppendAllText(@"c:\arquivo.txt", "NúmeroMatricula" + Environment.NewLine);

First, you will use the file writing method to perform the first storage of your enrollments.

Then, you should use the method to read the contents of the file and preferably convert it into concrete data (because everything will come as a string). Create objects, type data correctly.

Then increment the data via code and use the line inclusion method.

In all situations, you should analyze whether you will perform a test of file existence.

3

I decided to answer because although the other answer works, it has a wrong way of doing the operation. There are 2 problems.

First encourages the existence of a running condition when a file that did not exist exists exists between the check and its creation attempt. One might say that this is rare. It can in some situations, in others it doesn’t. So it’s better to teach people to do it the right way. Unfortunately the documentation does not help and teaches the wrong way.

And there is still an execution that closes the file independently, which will not occur if there is an exception.

So using the same example of the answer, the correct one would be something like this:

try {
    System.IO.File.WriteAllText(@"c:\arquivo.txt", "Matricula");
} catch (IOException ex) {
    WriteLine("deu erro"); //obviamente deve fazer outras coisas aqui
}

This is the safe (or almost, stay slow) way to perform this operation. Not only can there be the problem of running condition, but other problems may occur while running the WriteAllText(). Looking at the documentation of this method we see that it can fire several exceptions. Of course, you don’t need to treat them all individually and you may even stop treating them all, but you probably won’t have the best way to solve them when a problem occurs.

One thing that is very common is that the programmer creates the code, tests under controlled conditions and thinks everything is right. But it is necessary to test everything that can happen to him. One should force the execution of all possible exceptions, for example, and see what happens when they are fired. If the programmers are satisfied with everything, great. If they realize that what is happening under these conditions cannot happen exceptional, it needs to take action, need to change the code to treat this. In the case of exceptions is the use of try-catch which will allow a more granular treatment. Where to place it and for which exceptions, depends on each situation.

So keep in mind that the above example does not treat well either, because several other common exceptions have not been dealt with.

In some cases for each exception the code should take a different action. In this case you would need to have one catch for every possible exception (as per the documentation, programmer has to get used to reading documentation correctly). No secret.

In the case where it is possible to treat several exceptions with the same action, even C#5 was bad to treat because or did several catchs and replicated the action, even if it is called a standard method, or captured a generic exception and filtered with a if within the catch:

catch (Exception ex) {                
    if (ex is IOException || 
        ex is UnauthorizedAccessException || 
        ex is NotSupportedException || 
        ex is SecurityException || 
        ex is DirectoryNotFoundException || 
        ex is PathTooLongException) {
        WriteLine("deu erro");
    }
    throw;
}

In C# 6 it is possible to filter the exception according to reply from me in the OR:

catch (Exception ex) when (ex is IOException || 
                           ex is UnauthorizedAccessException || 
                           ex is NotSupportedException || 
                           ex is SecurityException || 
                           ex is DirectoryNotFoundException || 
                           ex is PathTooLongException) {
    WriteLine("deu erro");
}

I deliberately left the other two exceptions documented out since they are programming and not execution errors and should break the same application, ie should be treated elsewhere in a more generic way.

To make the addition in the text file one should observe the same situation, then possible exceptions in the AppendAllText() should be treated appropriately.

There are other ways to do this and depending on the situation may be preferable.

As well as to read the data there are several ways. One of them:

using (var fileStream = File.OpenRead(@"c:\arquivo.txt")) {
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize)) {
        while ((var line = streamReader.ReadLine()) != null) {
            //faz algo com a linha
        }
    }
}

I put in the Github for future reference.

Have more "ready" ways to do this but note the important use of using to ensure file closure even if an exception occurs.

Of course if you want to treat the exception better, it will replace the using by a try-catch.

See also the ReadLines() (the example in the documentation shows the use with try-catch but remember that it is only an example).

And obviously it is possible to read at once and avoid the using with the File.ReadAllText(). Of course, if there is a fault in it, it is necessary to treat it as well. The file may not exist at the time you open it. And I think I can already understand that if you check if it exists and then try to open it, it does not guarantee anything. For this there are exceptions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.