Remove a bit of a string before a word
24,620
try this
string s = oldString.Substring(oldString.IndexOf("Files"));
Thanks for Meta-Knight's comment,
if another "Files" can be in early part of the string then better would be..
string s = oldString.Substring(oldString.LastIndexOf("Files"));
Author by
Admin
Updated on February 26, 2020Comments
-
Admin about 4 years
I have string like this:
G:\Projects\TestApp\TestWeb\Files\Upload\file.jpg
How can I remove all text before "Files" (G:\Projects\TestApp\TestWeb)? The string before files can changed, so I can't count characters and remove them after 20 characters.
Thanks for your help :)
-
Mayo over 14 yearsThis is certainly valid, but I would like to add that you want to find a unique part of the string you want to keep (g:\uploadfiles\john\Files\Upload\ would fail). You could consider .jpg or \Files\Upload\ as well. Also, suggest .tolower() so you aren't impacted by case differences.
-
tsuo euoy over 14 yearsI would use LastIndexOf instead. It would minimize the risk of errors.
-
Charles Bretana over 14 years@Frozzare, be careful with this, in that if there can be another "Files" in the beginning somewhere, you may want to reverse the code as my edited answer shows.
-
PaulMcG over 14 yearsIn addition to using LastIndexOf, it's also a good idea to search for "\Files\" instead of just "Files" in case you have a path like "c:\My really important Files\Pictures\Files\Adult Files\NSFW" for instance.