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 catch
s 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.
Has this resolved? Can you accept any of the answers?
– Maniero