Reputation: 6320
Using Directory class library I am trying to retrieve all files Name existing in a Folder as below:
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(@"d:\Images\", "*.png");
foreach (string img in filePaths)
{
listBox1.Items.Add(img.ToString());
}
}
As you know this method returns Full path and name of the file but I need to get ONLY the name of files.Is it possible to do this in Directory Class? Do I have to use the Path class for this? if yes, how I can assign a path to a variable without file name? Thanks,
Upvotes: 2
Views: 2101
Reputation: 1
string aPath= @"course\train\yes\";
var fileNames=Directory.GetFiles(aPath).Select(name=>Path.GetFileName(name)).ToArray();
Upvotes: 0
Reputation: 67898
Try this:
using System.IO;
...
private void button1_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(@"d:\Images\", "*.png");
foreach (string img in filePaths)
{
listBox1.Items.Add(Path.GetFileName(img));
}
}
Upvotes: 2
Reputation: 28970
you can use Path.GetFileName
method
var file = Path.GetFileName(img);
Upvotes: 2
Reputation: 2251
From MSDN
string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''
Upvotes: 0
Reputation: 13696
Use DirectoryInfo
instead of Directory
. It returns a FileInfo
which you can get the Name
property of.
private void button1_Click(object sender, EventArgs e)
{
var filePaths = new DirectoryInfo.GetFiles(@"d:\Images\", "*.png").Select(x => x.Name);
foreach (string img in filePaths)
{
listBox1.Items.Add(img.ToString());
}
}
Upvotes: 0
Reputation: 11730
You can use
var files = Directory.EnumerateFiles(path,searchpattern);
var files = Directory.EnumerateFiles(@"C:\Users\roberth\Programming_Projects\Common\UI\bin\Debug\",
"*.xml");
var filename = new List<string>();
Console.WriteLine("Parsing Files...");
foreach (var file in files)
{
filename.Add(file);
Console.WriteLine("Parsing file: " + file);
....
Upvotes: 0