Ujjwal27
Ujjwal27

Reputation: 1153

How to pull the last before value from windows URL in C#?

I would like to know how can i get the value of last 2 nd part of the url ???

Input   : \\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello <br/>
Expected Output : 58

Please help me, on the code snippet.

Upvotes: 0

Views: 89

Answers (5)

Markus Johnsson
Markus Johnsson

Reputation: 4019

Use System.IO.Path:

var dir = Path.GetDirectoryName(@"\\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello");
// dir now contains \\\192.168.XX.XX\ABC\XYZZ\1234\58
var result = Path.GetFileName(dir)
// result = 58

Or shorter:

Path.GetFileName(Path.GetDirectoryName(@"\\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello"))

Upvotes: 2

sloth
sloth

Reputation: 101142

If you use the Uri class (which makes sense when working with URLs), you can make use of its Segments property:

var uri = new Uri(@"\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello");
var number = uri.Segments[uri.Segments.Length-2].TrimEnd('/');

Upvotes: 4

Hassan
Hassan

Reputation: 5430

You can use string.LastIndexOf(@"\") to get the index and call Substring

example:

string s = @"\\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello";
string ns = s.Substring(s.LastIndexOf(@"\") + 1); //Hello

UPDATE:

Use Split to get 2nd Last backslash:

 string[] arr = s.Split('\\');
 ns = arr[arr.Length - 2]; //58

Upvotes: 1

Dhaval Patel
Dhaval Patel

Reputation: 7601

You can use substring method.

        string s=@"\192.168.XX.XX\ABC\XYZZ\1234\58\Hello";
        var abc = s.Substring((s.LastIndexOf("\\")-2), 2);

Upvotes: 0

Adil
Adil

Reputation: 148150

You can use string.Split

string str = @"\\\192.168.XX.XX\ABC\XYZZ\1234\58\Hello <br/>";
var arr = str.Split('\\');
string val = arr[arr.Length-2]; 

Upvotes: 2

Related Questions