-1

I want to get the file name resides under a specified folder.

i.e. there is a file stored under two folders First\Second\test.txt I want have the path of the parent directory of file that is First\Second\ in my program. Now I want to get the file name residing under the directory "Second" using code.

Please help me.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Mohemmad K
  • 809
  • 7
  • 33
  • 74
  • What do you exactly need? do you want to get all the files from `second` folder, or do you want to get the filename from path, your question is not really clear – Habib Feb 18 '13 at 10:19
  • There only single file resides in second folder. That file name I want to get. @Habib – Mohemmad K Feb 18 '13 at 10:22

3 Answers3

1

You can use Directory.GetFiles method to get the files in directory with complete path and later use these files path to extract files names.

string [] fileEntries = Directory.GetFiles(targetDirectory);

To get the files names without path you can use linq

var fileNames System.IO.Directory.GetFiles(targetDirectory).Select(c => Path.GetFileName(c)).ToList();
Adil
  • 146,340
  • 25
  • 209
  • 204
  • This will get the full file paths. Not the file names. My answer below will get just the names. You need the Path.GetFileName call. – Sam Shiles Feb 18 '13 at 10:23
  • 1
    I did not look at your answer dear, just realized from your comment that my answer is not getting files names. – Adil Feb 18 '13 at 10:30
1

The following will do the trick if you want one file.

using System.IO; 
using System.Linq

var file = Directory.GetFiles("C:\\First\\Second\\").FirstOrDefault();

if (file != null)
{
    var fileName = Path.GetFileName(file);
}

The following will get you all the file names:

using System.IO; 
using System.Linq

var files = Directory.GetFiles("C:\\First\\Second\\");
var fileNames = files.Select(f => Path.GetFileName(f));
Sam Shiles
  • 10,529
  • 9
  • 60
  • 72
0

Here you go:

1)

string sourceDir = @"C:\First\Second\";
string[] fileEntries = Directory.GetFiles(sourceDir);

foreach(string fileName in fileEntries)
{
   // do something with fileName
   Console.WriteLine(fileName);
}

2)

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location);
foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
{ 
    Console.WriteLine(f.Name); 
}
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105