Friday, January 27, 2012

C# getting file names without extensions


When you walk a directory getting file names you get a file name with its extension: file1.txt, file2.txt, file3.txt.
How can you get file names without file extensions file1, file2, file3?

DirectoryInfo d = new DirectoryInfo(myDirectory);
FileInfo[] fileArrray = d.GetFiles("*.txt");
foreach (FileInfo f in smFiles)
{
   var fileNameOnly = Path.GetFileNameWithoutExtension(f.Name);
   
   //...
   //process file...
}

Thre is also a linq way:

var filenames = String.Join(", ", Directory.GetFiles(@"c:\", "*.txt")
.Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray());

Submit this story to DotNetKicks

No comments:

Post a Comment