Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string in string

Tags:

string

c#

I'm having troubles insert a substring in a string what I want is to inject "/thumbs" into a stringpath

/media/pictures/image1.jpg

I want to inject /thumbs/ into the last part of the path like this:

/media/pictures/thumbs/image1.jpg

Is it possible with linq?

like image 717
Gmorken Avatar asked Jun 08 '26 16:06

Gmorken


2 Answers

For something like path manipulation, it's best to use the System.IO namespace, specifically the Path object. You can do something like;

string path = "/media/pictures/image1.jpg";
string newPath = Path.Combine(Path.GetDirectoryName(path), "thumbs", Path.GetFileName(path)).Replace(@"\", "/");
like image 188
DiskJunky Avatar answered Jun 11 '26 04:06

DiskJunky


Try this, you get the index of the last forward slash and insert the additional string at that point.

Unsure as to why the downvote, but I assure it works.

string original = "/media/pictures/image1.jpg";
string insert = "thumbs/";
string combined = original.Insert(original.LastIndexOf("/") + 1, insert);
like image 22
Adam K Dean Avatar answered Jun 11 '26 04:06

Adam K Dean