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

时间:2017-06-11 13:57:09

标签: c# batch-file console-application enumeration

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

我试图为某个扩展类型的每个文件枚举一个目录。存储路径时,文件名和变量中当前文件的扩展名。然后将该信息发送到cmd.exe以获取每个文件。但是,我无法弄清楚如何正确循环它。我也不认为我已经拥有的代码是正确的。

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

I节努力复制的例子:

@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;

2 个答案:

答案 0 :(得分:1)

尝试类似下面的内容,看看它是否适合您。

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 .....");
    }

答案 1 :(得分:1)

我对批处理文件不太满意,但是我能说流利的C#。该程序将在.patch中找到所有pathDir文件的路径,然后为每个文件路径创建一个命令字符串,并使用该命令启动一个新的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博士的回答有所不同:

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