2011-06-13 154 views
3

我正在寻找一种方法来读取目录路径中的所有txt文件,而不需要将它们扩展到数组中。我查看了path.getFileNameWithoutExtension,但只返回一个文件。我想从一个路径上的所有* .txt文件名我指定C#获取所有没有目录扩展名的文件名

感谢

回答

13
Directory.GetFiles(myPath, "*.txt") 
    .Select(Path.GetFileNameWithoutExtension) 
    .Select(p => p.Substring(1)) //per comment 
+0

还有一个要求是我需要修剪所有文件名中的第一个字符。我该怎么做呢? – hWorld 2011-06-13 20:48:02

+0

单个选择比两个效率更高^^ – Falanwe 2011-06-13 20:54:58

+0

您的问题有点不清楚。 'filename.Substring(0,1)'只会给你第一个字符。 'filename.Substring(1)'会给你一切,但第一个字符。 – David 2011-06-13 21:00:30

5

喜欢的东西:

String[] fileNamesWithoutExtention = 
Directory.GetFiles(@"C:\", "*.txt") 
.Select(fileName => Path.GetFileNameWithoutExtension(fileName)) 
.ToArray(); 

应该做的伎俩。

0
var filenames = Directory.GetFiles(myPath, "*.txt") 
.Select(filename => Path.GetFileNameWithoutExtension(filename).Substring(1)); 

(子串(1))加入用于解说的规范)

0
var files = from f in Directory.EnumerateFiles(myPath, "*.txt") 
      select Path.GetFileNameWithoutExtension(f).Substring(1); 
0

只是需要将其转换为阵列[]

string targetDirectory = @"C:\..."; 

// Process the list of files found in the directory. 
    string[] fileEntries = Directory.GetFiles(targetDirectory, "*.csv").Select(Path.GetFileNameWithoutExtension).Select(p => p.Substring(0)).ToArray(); 

    foreach (string fileName in fileEntries) 
     { 
      //Code 
     } 
相关问题