user1358072
user1358072

Reputation: 447

How to remove end of string (fileName) using substring?

I know I must use Substring to remove, but I dont know how to do this. I need to remove end of string like this

from

"C:\\Users\\myname\\Pictures\\shoeImage.jpg"

to

"C:\\Users\\myname\\Pictures"

Upvotes: 3

Views: 420

Answers (4)

Haney
Haney

Reputation: 34832

If you want to substring it:

var subString = yourString.SubString(0, yourString.LastIndexOf('\\'));

Upvotes: 1

Soner Gönül
Soner Gönül

Reputation: 98770

You can use Path.GetDirectoryName method.

Returns the directory information for the specified path string.

Console.WriteLine(Path.GetDirectoryName("C:\\Users\\myname\\Pictures\\shoeImage.jpg"));

It returns this;

C:\Users\myname\Pictures

Here a DEMO.

With String.SubString method, you can use it like;

string path = "C:\\Users\\myname\\Pictures\\shoeImage.jpg";
Console.WriteLine(path.Substring(0, path.LastIndexOf(@"\")));

Upvotes: 4

brunnerh
brunnerh

Reputation: 184947

Use the methods of the System.IO.Path class instead, in specific GetDirectoryName.

Upvotes: 9

Rohit Vats
Rohit Vats

Reputation: 81243

You should use FileInfo in such scenarios -

FileInfo info = new FileInfo("C:\\Users\\myname\\Pictures\\shoeImage.jpg");
string name = info.DirectoryName;

OR

Path.GetDirectoryName("C:\\Users\\myname\\Pictures\\shoeImage.jpg");

Upvotes: 3

Related Questions