Get the folder with the file.

I have a folder fuill images and has the image name and full path to the file stored in an array in my program. Is it possible to get only the folder and file name from the file path.

So, if I have a file path

C:\Users\Ryan\Documents\myImage.jpg 

I need to get

 Documents\myImage.jpg 
+5
source share
4 answers

Use this code:

 FileInfo f = new FileInfo(@"C:\Users\Ryan\Documents\myImage.jpg"); string result = Path.Combine(f.Directory.Name, f.Name); 
+7
source

The Path class has methods for working with file names:

 var path = @"C:\Users\Ryan\Documents\myImage.jpg"; var fileName = Path.GetFileName(path); var directoryName = Path.GetDirectoryName(path); var lastDirectoryName = Path.GetFileName(directoryName); var result = Path.Combine(lastDirectoryName, fileName); 
+2
source
 var pathParts = filepath.split('\\'); var lastPath = pathParts[pathParts - 2] + @"\" + pathParts[pathParts - 1]; 
0
source

It's just a string game, but it does the job

  string path = "C:\Users\Ryan\Documents\myImage.jpg"; string[] temp = path.Split('\'); string folder = temp[temp.Length - 2] + @"\" + temp[temp.Length - 1]; 
0
source

Source: https://habr.com/ru/post/1236412/


All Articles