How to know if path exists?

8

One of my system classes is created with information from a file.

When you start the system, it initially runs the following lines:

public List<Estabelecimento> listaEstabelecimento(string ibge)
{
    List<Estabelecimento> listaestabelecimento = new List<Estabelecimento>();
    var caminho = HttpContext.Current.Server.MapPath("~/Content/txtCnes/" + ibge);
    //como saber se a variável 'caminho' é um diretório válido? caso não seja, como criá-lo?
    StreamReader file = new StreamReader($"{caminho}/lfces004.txt", Encoding.GetEncoding("iso-8859-1"));

I want to know if the caminho variable is a valid directory, and if not, I want the system to create it.

    
asked by anonymous 05.10.2017 / 17:03

1 answer

15

By the code presented the correct way to handle this is by capturing the exception generated after trying to use the path. Failure to do so may incur race condition , so other forms produce codes that work most of the time, but may so it is wrong programming.

Who knows me here knows that I refuse the abuse of exceptions, but this is one of the cases that the exception is the best mechanism and interestingly the programmers refuse to use.

Then it would look like this:

public List<Estabelecimento> listaEstabelecimento(string ibge) {
    List<Estabelecimento> listaestabelecimento = new List<Estabelecimento>();
    var caminho = HttpContext.Current.Server.MapPath("~/Content/txtCnes/" + ibge);
    //como saber se a variável 'caminho' é um diretório válido? caso não seja, como criá-lo?
    try {
        var file = new StreamReader($"{caminho}/lfces004.txt", Encoding.GetEncoding("iso-8859-1"));
        // provavelmente terá algo para fazer aqui para fazer sentido
    } catch (DirectoryNotFoundException) {
         WriteLine("o caminho não existe");
         return null; // provavelmente, não vi todo o código
    }

If you want you can handle other exceptions that this code can generate as shown by documentation . If you want other behavior you have to adapt or it would have to be explicit in the question. The answer was given to what was asked.

Note that I do not know and should not try to catch an exception for this case, if the question were clearer about the context and purpose I could give a more precise answer.

If it were the case of creating a directory only, as there was in another answer now deleted, besides not having to check anything or need to treat exception to know if the directory exists or not, because if it exists does not give error, it just use what already exists. If it does not exist it creates. Just this.

There has been a contested, now erased, contention that there is a race condition problem in the path generation before attempting to access the directory, but it does not matter, only access will generate a problem, any manipulation of the path text causes no problem of race condition because the text is not the external resource, the directory is that it is the external resource and naturally shared. What is not shared never generates a race condition.

That's why I I asked what the goal was . With the edition it was clear that there would be race condition. If it just wanted to know if the directory exists or not and was not going to use it directly then Directory.Exists() " would be adequate, so it exists. What you can not do is take your existence and use this condition to take an action that depends on it continuing the same. This is race condition.

I understand that even experienced programmers often err in race condition because it is complicated and difficult to reproduce when it is not properly handled. As it is more common it does not run than occur the programmers think that it has no problem not to treat properly. Until that happens and then it gets flattened that it's bug from the compiler, from the operating system or something like that. I recommend re-read or ask specific race condition questions .

    
05.10.2017 / 17:36