简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM