How to know if path exists?

Asked

Viewed 332 times

11

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

When starting 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 variable caminho is a valid directory, and if not, I want the system to create it.

  • And why do you want to know if it’s valid? Do you need this information or do you need something else and do you think it will be useful? You don’t usually need to know that. It’s use and good. If it gives error you treat. Usually solutions that try to know if it is valid is programming error, although almost everyone commits it.

  • 1

    Italo even left the way you edited, but, do not withdraw the namespaces many do not know where is each command is important always a complete answer ... ! blz! I did that way to demonstrate more what should happen, as simply as possible. from a general context

  • Why create the directory in case of its non-existence?

  • 1

    Because I will create some files inside the directory

  • 3

    @Italorodrigo So it’s really what I suspected, you don’t need to know if it exists, you need to try to create and treat if it goes wrong, so I responded in the proper way to do this.

1 answer

18


By the code presented the correct way to treat this is by capturing the exception generated after trying to use the path. Not doing this may incur running condition, so other forms produce codes that work most of the time, but may fail, so it’s wrong programming.

Those who know me here know that I refute 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
    }
}

I put in the Github for future reference.

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

Note that I don’t even know if I should try to capture an exception for this case, if the question was clearer as to the context and objective I could give a more precise answer.

If it were the case to create a directory only, as there was in another answer now deleted, besides not need to check something or need to treat exception to know if the directory exists or not, because if it exists does not give error, it just uses what already exists. If there is no he creates, only this.

There was a dispute, now deleted, about there being a race condition problem in the path generation before trying to access the directory, but no matter, only the access will generate a problem, any manipulation of the path text does not cause race condition problem because the text is not the external resource, the directory is the external resource and naturally shared. What is not shared never generates a running condition.

That’s why I I asked what was the point. With the edition it was clear that there would be race condition. If he only wanted to know if the directory exists or not and would not use it directly then the Directory.Exists() That’s why it exists. What you cannot do is take your existence and use this condition to take an action that depends on it to remain the same. That’s race condition.

I understand that even experienced programmers often make mistakes in running condition because it is complicated and difficult to reproduce when it is not properly treated. As it is more common not to run than occur programmers think it is okay not to treat properly. Until it happens and then it’s like bug compiler, operating system or something like that. I recommend reread or ask new specific questions about race condition.

Browser other questions tagged

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