C# - 枚举特定文件类型的目录,然后循环使用每个文件

C# - Enumerate directory for specific filetype then use each file in loop

本质上,我正在尝试将我的代码从批处理文件 (.bat) 迁移到 C# 控制台应用程序。我正在使用 Visual C# 2010 Express。主要功能是用于许多命令行实用程序的基于 TUI 的助手。我的问题应该很简单。但是我一个人一直无法解决。

我无法为每个特定扩展类型的文件枚举一个目录。在变量中存储当前文件的路径、文件名和扩展名。然后将每个文件的信息发送到 cmd.exe。但是我不知道如何正确循环它。我也不认为我已有的代码是正确的。

string patches = Directory.GetFiles(pathDir, "*.patch"); returns System.String[]

我正在努力重现的部分中的示例:

@echo off
SETLOCAL EnableDelayedExpansion

:: Variables hardcoded for the sake of example.

:: Folder containing patches
set "pathDir=C:\Main\Directory\Path\External"
:: File to apply patches on
set "varFile=C:\Main\Directory\Path\file.tmp"
:: Utility that applies patches
set "progExt=C:\Main\Directory\Path\Program.exe"
cls

:: Main loop
For /F "delims=" %%A In ( ' DIR /B /O:N /A:-D "%pathDir%\*.patch" ' ) Do (
  :: Announce current filename
  echo Patching %%A
  :: Any key to contine - Makeshift confirmation without cancel
  pause
  :: Arguments to invoke external application
  "%progExt%" "%pathDir%\%%A" "%varFile%"
:: End Loop
)
cls

到目前为止,我在 C# 中掌握的这部分内容:

string pathDir = @"C:\Main\Directory\Path\External";
string varFile = @"C:\Main\Directory\Path\file.tmp";
string progExt = @"C:\Main\Directory\Path\Program.exe";
string patches = Directory.GetFiles(@pathDir, "*.patch");
// Set variable for current file - Missing
string cmdDebug = "/C echo "; // enable with IF statements later
System.Diagnostics.Process.Start("CMD.exe", cmdDebug + pathDir + "&& echo " + varFile + "&& echo " + progExt + "&& echo " + patches + "&& pause");
// System.Diagnostics.Process.Start("CMD.exe","/C " + progExt + " " + curPatch + " " + varFile";

这些也是我的收录:

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;

试试下面的方法看看是否适合你。

private void GetFiles()
{
    DirectoryInfo DIRINF = new DirectoryInfo("C:\STAIRWAYTOHEAVEN");
    List<FileInfo> FINFO = DIRINF.GetFiles("*.extension").ToList();
    List<object> Data = new List<object>();
    foreach (FileInfo FoundFile in FINFO)
    {
        // do somthing neat here.
        var Name = FoundFile.Name; // Gets the name, MasterPlan.docx
        var Path = FoundFile.FullName; // Gets the full path C:\STAIRWAYTOHEAVE\GODSBACKUPPLANS\MasterPlan.docx
        var Extension = FoundFile.Extension; // Gets the extension .docx
        var Length = FoundFile.Length; // Used to get the file size in bytes, divide by the appropriate number to get actual size.

        // Make it into an object to store it into a list!
        var Item = new { Name = FoundFile.Name, Path = FoundFile.FullName, Size = FoundFile.Length, Extension = FoundFile.Extension };
        Data.Add(Item); // Store the item for use outside the loop.
    }
}

编辑:为了进一步提供帮助,您可以像下面这样访问文件信息,以便遍历每个文件。

    foreach (dynamic Obj in Data) // Access the properties via a dymanic object so there isn't a huge conversion process with propertyinfo
    {
        System.Diagnostics.Process.Start("cmd.exe", "/c echo " + Path.GetDirectoryName(Obj.FullName) + "&& echo .....");
    }

我不太擅长批处理文件,但 C# 很流利。该程序将找到pathDir中所有.patch个文件的路径,然后为每个文件路径创建一个命令字符串,并使用该命令启动一个新的CMD进程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.IO;

static class Program {

    static void Main()
    {
        var pathDir = @"C:\Main\Directory\Path\External";
        var varFile = @"C:\Main\Directory\Path\file.tmp";
        var progExt = @"C:\Main\Directory\Path\Program.exe";

        var commandBase = string.Format("/C echo {0} && echo {1} && echo {2} && echo ",
            pathDir, varFile, progExt);

        var commands = Directory
            .GetFiles(@pathDir, "*.patch")
            .Select(file => string.Format("{0}{1}&& pause", commandBase, file));

        foreach (var c in commands){
            Process.Start("CMD.exe", c);
        }
    }
}

虽然我不能 100% 确定它是否符合您原始文件的逻辑。


值得指出的几点与 FeelGood 博士的回答不同:

  • 因为GetFilesreturns是一个数组,所以不需要转换成List。 .NET List 基本上是 Array 的包装器,允许调整 collection.
  • 的大小
  • Directory.GetFiles returns 路径字符串数组,而不是 DirectoryInfo.GetFiles 其中 returns FileInfo objects。 Directory 是一个用于操作目录的静态 class,而 DirectoryInfo 是一个实例 class,其中每个实例代表一个目录。
  • 如果使用 DirectoryInfo/FileInfo,则无需创建单独的 objects 来封装每个文件的详细信息,因为它们最终只是变成了字符串。 (此外,FileInfo 已经是相同的抽象。)直接转换为字符串更有效。
  • Select 方法 returns 一个 IEnumerable<T> 这是一个惰性序列,这意味着所有文件路径不会立即转换为格式化字符串,它们一次格式化为该序列由 foreach 循环消耗。如果您的 collection 很小(可能少于 500 件),您可能看不出有什么不同,但如果它很大,则可以节省时间。
  • Select 创建的 IEnumerable 直接送入 foreach 循环避免创建另一个 Listdata 在上一个答案中)。