Remove half of the file name

Asked

Viewed 124 times

-2

I have a page to pick up a path, which is the Folder Browser Dialog and the path that is saved is like this : "C: ana Updates 2017 2017_04\"

I wanted to go through the path, save only the result in a variable : 2017 2017_04.

  • What is the criterion for choosing what to take? It’s the last 2, it’s all that comes after the fifth level. Is it after a certain name? It’s by a specific pattern?

  • After a given name, which in this case is the "updates"

  • Hello Ana, If the doubt has to do with this question, post the complete path to avoid inconvenience. If this is the complete path, disregard this message.

2 answers

7


If you want to capture only what comes after "Updates", as was said in the comments just capture the position in which the keyword ("updates", in case) lies within the full path and work on a substring.

Note that the second parameter of LastIndexOf causes the Casing is ignored in the comparison. If you do not want this behavior, just delete this parameter.

string palavraChave = "Updates";
var dir = @"C:\ByMe\SOLUTIONS\Dictation1\Database\Updates\2017\2017_04\";

var index = dir.LastIndexOf(palavraChave, StringComparison.CurrentCultureIgnoreCase);

var resultado = dir.Substring(index + palavraChave.Length + 1);

Console.WriteLine(resultado);

// A saída será 2017\2017_04\

See working on . NET Fiddle.

7

A naive solution would be to use the Split(). In fact any solution that tries to find a text pattern runs the risk of 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 start being equal, then instead of filtering through \Updates could filter through C:\ByMe\SOLUTIONS\Dictation1\Database\Updates\ that there will be no risk. Even if varying a part it would be better to build this whole text only with the part that varies differently.

It is probably not of interest to you, but in some cases generalizing the separator 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 are many things ready and done better than most programmers can do.

using static System.Console;
using System;

public class Program {
    public static void Main() {
        var dir = @"C:\ByMe\SOLUTIONS\Dictation1\Database\Updates\2017\2017_04\";
        var partes = dir.Split(new string[] { @"\Updates\" }, StringSplitOptions.None);
        WriteLine(partes[1]);
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

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