-3

How do I get the folder name from my path?

This is the file path:

@"C:\Users\ME\Desktop\videos"

Under the main path there's a folder that I want to get the name:

@"C:\Users\ME\Desktop\videos\sample2"
@"C:\Users\ME\Desktop\videos\sample3"
@"C:\Users\ME\Desktop\videos\sample4"

Under the sample folder, there are videos that I want to get the name:

@"C:\Users\ME\Desktop\videos\sample1\video1.mp4

This is my code:

foreach(string s in Directory.GetFiles(@"C:\Users\ME\Desktop\videos").Select(Path.GetFileName))
{
    MessageBox.Show(s);
}

Is this possible? How do I get the name of every file that exists inside my video/main folder using only the main path?

MethodMan
  • 18,625
  • 6
  • 34
  • 52
Volkswagen
  • 155
  • 2
  • 4
  • 11

2 Answers2

6

Do this

string[] files = Directory.GetFiles(@"C:\Users\Me\Desktop\Videos", "*.mp4", SearchOption.AllDirectories)

foreach (string file in files)
{
    MessageBox.Show(Path.GetFileName(file));
}

If you're trying to get the folder name from a full files path then do this

Path.GetFileName(Path.GetDirectoryName(file))
adv12
  • 8,443
  • 2
  • 24
  • 48
3

Use System.IO.Directory.GetFiles

var files = System.IO.Directory.GetFiles(
  "@"C:\Users\ME\Desktop\videos", 
  "*.mp4",
  System.IO.SearchOption.AllDirectories)
gnud
  • 77,584
  • 5
  • 64
  • 78