I have a page to get a path, which is Folder Browser Dialog
and the path that is saved is like this: "C: \ ana \ Updates \ 2017 \ 2017_04 \"
I wanted from the path to save in a variable only the result: 2017 \ 2017_04.
I have a page to get a path, which is Folder Browser Dialog
and the path that is saved is like this: "C: \ ana \ Updates \ 2017 \ 2017_04 \"
I wanted from the path to save in a variable only the result: 2017 \ 2017_04.
If you want to capture only what comes after "Updates", as has been said in the comments, just capture the position where the keyword ("updates" in the case) lies within the complete path and work on a substring .
Note that the second parameter of LastIndexOf
causes casing to be ignored in the comparison. If you do not want this behavior, just remove this parameter.
string palavraChave = "Updates";
var dir = @"C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04\";
var index = dir.LastIndexOf(palavraChave, StringComparison.CurrentCultureIgnoreCase);
var resultado = dir.Substring(index + palavraChave.Length + 1);
Console.WriteLine(resultado);
// A saída será 201717_04\
A naive solution would be to use Split()
. In fact any solution that tries to find a text pattern risks going wrong unless it has guarantees of what it will find or the criterion is very well defined, solving all possible ambiguities. It would be better if you could guarantee the entire beginning being equal, then instead of filtering by \Updates
could filter by C:\ByMe\SOLUTIONS\Dictation1\Database\Updates\
that there will be no risk. Even if you vary a part it would be better to build this whole text only with the part that varies differently.
It is probably not in your interest, but in some cases generalizing the tab may be useful for the code to be more portable. See Path.DirectorySeparatorChar
.
Not for this case, but keep an eye on the class Path
when dealing with file paths, there is a lot more ready and done that most programmers can do.
using static System.Console;
using System;
public class Program {
public static void Main() {
var dir = @"C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04\";
var partes = dir.Split(new string[] { @"\Updates\" }, StringSplitOptions.None);
WriteLine(partes[1]);
}
}
See running on .NET Fiddle . And at Coding Ground . Also I put it in GitHub for future reference .