Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Remove URL from String

Tags:

string

c#

This seems like a really easy one but everything I try doesn't seem to work

say I have the following string:

string myString = "http://www.mysite.com/folder/file.jpg";

How can I process that to remove the URL and just leave "file.jpg" as the string value?

Thanks!

Kris

like image 769
lookitskris Avatar asked Feb 10 '26 22:02

lookitskris


2 Answers

You can always use System.IO.Path methods

string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg

If you do want to process more complex URIs you can pass it thought the System.Uri type and grab the AbsolutePath

string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);
like image 153
Matthew Whited Avatar answered Feb 15 '26 02:02

Matthew Whited


string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);
like image 23
LukeH Avatar answered Feb 15 '26 01:02

LukeH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!