Search code examples
c#regexreplaceruntime-errorsystem

When i try to use Regex.Replace it throws out System.ArgumentException


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.


Solution

  • 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;
      }