Write and retrieve information in files

1

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

I have an enrollment system. Start a folder in Windows and within it I generate the registrations sequentially. I finish and go home and the next day, I will generate new set of registrations, but I must start from the last and go adding another: matricula_atual + 1 . I need to keep recording on it without losing what already existed.

How do I write the file to a folder?

    
asked by anonymous 21.07.2015 / 13:53

2 answers

3

Test if file exists:

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

Perform multi-line writing on file (overwrite content):

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

Read text file content:

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 registrations.

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

Then, code increment the data and use the line-in method.

In all situations, you should consider whether to perform a test of the existence of the file.

    
21.07.2015 / 14:25
3

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

First encourage the existence of a race condition when a file that does not exist passes between the verification and its creation attempt. One can say that this is rare. It can in some situations, in others not. 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's 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 look 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, continue slow) way to perform this operation. Not only can there be the race condition issue, but other issues can occur while running % with% / a>. Looking at the documentation of this method we see that it can trigger several exceptions. Of course you do not have to treat all of them individually and may even stop treating them all, but you probably will not have the best way to resolve them when a problem occurs.

One thing that is very common is the programmer creating the code, testing under controlled conditions and finding that everything is right. But you need to test everything that can happen to him. You should force yourself to execute all possible exceptions, for example, and see what happens when they are fired. If the programmers are happy with everything, great. If he realizes that what's going on under these exceptional conditions can not happen, he needs to take action, he needs to change the code to handle this. In the case of exceptions is the use of WriteAllText () that will allow a more granular treatment. Where to put it and for which exceptions, depends on each situation.

So keep in mind that the above example does not handle well too, because several other common exceptions have not been addressed.

In some cases, for each exception, the code must take a different action. In this case you would need to have a try-catch for each possible exception (according to the documentation, programmer has to get used to reading documentation correctly). No secrets.

In cases where it is possible to handle several exceptions with the same action, until C # 5 was bad to handle because it made several catch if it replicated the action, even if it was calling a standard method, or caught an exception generic and filtered with catch within if :

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 you can filter the exception as my answer in the SO :

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 from the outside since they are programming errors and not execution errors and should break the application itself, ie they should be treated elsewhere in a more generic way.

To do the addition in the text file you should observe the same situation, so the possible exceptions in catch should be handled properly.

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

As well as reading the data there are also 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
        }
    }
}

There are more "ready" ways to do this, but note the important use of AppendAllText() to ensure file closure even if an exception occurs.

Of course, if you want to treat the exception better, it will replace using with using .

See also try-catch (the example in the documentation shows usage with ReadLines() but remember it's just an example).

And of course you can read at one time and avoid try-catch with using ". Of course, if there is any flaw in it, it is necessary to treat it as well. The file may not exist at the time it opens. And I think you've already understood that if you check it out and then try to open, it does not guarantee anything. For this there are exceptions.

    
21.07.2015 / 16:37