-2

I have this peace of code:

string modz = Regex.Replace(mod, Directory.GetCurrentDirectory(), "");

mod string is essentially like this:

C:\Users\USER\Documents\SharpDevelop Projects\Project\Project\bin\Debug\BALZOO.jar

and i want it to be BALOO.jar or just BALZOO.

GSerg
  • 76,472
  • 17
  • 159
  • 346
Boso Yolo
  • 5
  • 3
  • 3
    Why do you think that the result of `Directory.GetCurrentDirectory()` will be a valid regex pattern? If you wanted to replace a dumb string in a dumb string, surely you would use [`String.Replace`](https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-6.0)? And if you know it's a path from which you want the file name, surely you would [use](https://stackoverflow.com/q/6921105/11683) `Path.GetFileName`? – GSerg May 21 '22 at 20:54

1 Answers1

1

Like @GSerg pointed out, a typical directory path is unlike to be a valid regex pattern, and even if it is, it is unlikely to do the replace like you would expect. You should use the plain string.Replace instead.

However, there are better approaches than string replacement. Depending on what you like to do:

  1. to obtain the file name only:

    Path.GetFileName(mod) // BALOO.jar
    Path.GetFileNameWithoutExtension(mod) // BALOO
    
  2. to obtain the relative path to mod from current directory:

    MakeRelative(mod, Directory.GetCurrentDirectory())
    // ...
    public static string MakeRelative(string path, string relativeTo)
    {
        return new Uri(relativeTo).MakeRelativeUri(new Uri(path)).OriginalString;
    }
    
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44