Path of the previous folder

10

How can I get the path of the previous folder? For example I have this path: C:/Pasta1/Pasta2
And I wanted to get the folder path 1 C:/Pasta1
How can I do this?

    
asked by anonymous 06.10.2017 / 15:14

2 answers

12

I believe you want GetParent() .

using static System.Console;
using System.IO;

public class Program {
    public static void Main() {
        WriteLine(Directory.GetParent("/Pasta1/Pasta2"));
    }
}

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

Just be careful if you end up with a slash because it will cause the stream to be nothing, and the last one listed is the parent. If situation can occur so it is best to treat it properly.

There was a challenge, now erased, that would generate a race condition in this code. This is just text, not a shared external resource, it is not the directory. Only shared resources generate a race condition. Of course a later use of this text to access the directory may eventually generate a race condition, but I can not know this since I do not even know how this text was obtained. If it has been typed, if it is hard-coded in the code or file it will not generate race condition because it is just text. The race condition only happens if you take an existing state on a shared resource and then try to access it without knowing if it is still in the same state when you expect to be in the same state.

The question does not tell you where this data comes from or how it will be used. It is obvious that if this is used and the directory does not exist it will give an error and this should be handled. This does not generate race condition, but an access failure may occur.

If you attempt to access, generate an access error, and are handled by capturing the exception there is no race condition. If you check if the directory exists and then try to access, there is race condition. For this reason a large number of users have mistakenly considered a answer in another question from the one who answered here , and which has now been deleted, which checks before using.

For those who have not yet understood race condition I advise you to read and reread the post , and ask more specific questions , on the subject, the subject is difficult even.

    
06.10.2017 / 15:17
5

Here is an example of using GetParent() of class System.IO.Directory

var caminho1 = Directory.GetParent("C:\Pasta1\Pasta2");
//caminho1 = "C:\Pasta1"
    
06.10.2017 / 15:25