文件计数开始于

File count starting with

我需要生成一条消息来计算以指定名称开头的文件的数量。

代码如下:

Private void button1_click (...)
{
      // this is the code to count the number of files that start with a specified string
      String Path = "..."
      int fCount = Directory.GetFiles (path,"InsertImage", SearchOption.AllDirectories).Length;

      messageBox.Show("fCount");
}

它不适合我的目的。有什么建议吗?

试试这个:

string[] files = Directory.Getfiles(path);
for(int i = 0; i < files.length; i++)
{
    if(files[i].StartsWith("string"))
    {
         // then do some work
    }
}

如果你这样做,你将不必在内存中拥有整个文件列表:

string path = "...";
string target = "InsertImage*"; // <--- NOTE THE "*"

var matchingFiles = Directory.EnumerateFiles(path, target, SearchOption.AllDirectories);
int count = matchingFiles.Count();

Console.WriteLine(count);
int count=Directory.GetFiles(path, SearchOption.AllDirectories).Where(x => x.StartsWith(searchstring)).Count();

这应该有效。

编辑现有代码:

int fCount= Directory.GetFiles(path, "InsertImage*", SearchOption.AllDirectories).Length;
messageBox.Show(fCount);

注:

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directory and sub directories

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly).Length; // Will Retrieve count of all files in directory but not sub directories

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directory and sub directories