-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.

4

3 回答 3

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();
于 2013-02-18T10:15:51.183 回答
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));
于 2013-02-18T10:15:59.153 回答
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); 
}
于 2013-02-18T10:16:38.733 回答