How to compare directory path names?

Asked

Viewed 79 times

0

I have two paths:

  1. C:\\anacarvalho\\Database\\Updates\\2017\\2017_04\\20170419_AC - Path selected by a Folder browser dialog.
  2. C:\\anacarvalho\\Database\\Updates - Path that is at the root of the system.

I need a way, that tells me if the path that was selected by Folder browser dialog, contains the same beginning of path 2. In this case you have to tell me that until the Updates is equal.

Can someone help me ?

1 answer

3

You can do it this way:

string caminho = "C:\\anacarvalho\\Database\\Updates\\2017\\2017_04\20170419_AC";
string raiz = "C:\\anacarvalho\\Database\\Updates";
if (caminho.Contains(raiz))
{
//Código aqui.
}

Or that:

string caminho = "C:\\anacarvalho\Database\\Updates\\2017\2017_04\\20170419_AC";
string raiz = "C:\\anacarvalho\\Database\\Updates";
if(caminho.IndexOf(raiz,StringComparison.OrdinalIgnoreCase) != -1)
{
//Código aqui.
}

See working on Ideone.

  • Why aren’t you the best? It’s simple, minimalist and repurposes the implementation of the platform. You have my upvote.

  • I had put it because I didn’t know if there is a specific function for it. Anyway I edited my post, thanks.

  • The only change I would make would be to use StartsWith instead of Contains, and in the second example ensure that the index is igual a zero instead of diferente de menos um.

Browser other questions tagged

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