c语言glob函数头文件,如何在C中实现glob#

此博客介绍了如何在C#程序中利用PowerShell的`Get-ChildItem`(别名`dir`)cmdlet来实现文件遍历和搜索。通过创建并打开一个Runspace,切换到指定目录,然后执行`dir`命令,可以找到匹配特定通配符的文件路径。示例代码展示了如何获取所有`.txt`文件和`.exe`文件的完整路径,并在控制台中打印出来。
摘要由CSDN通过智能技术生成

You can use the "dir" (aka "Get-ChildItem") powershell cmdlet from C#.

(I'm not saying whether you should.)

You have to add this reference to your project file (".csproj" or ".vcproj") manually:

See here for more details on how to use cmdlets from C#: http://www.devx.com/tips/Tip/42716

Here a working program:

using System;

using System.Collections.Generic;

using System.Management.Automation;

using System.Management.Automation.Runspaces;

using System.Collections.ObjectModel;

namespace CsWildcard {

class Program {

static IEnumerable CmdletDirGlobbing(string basePath, string glob){

Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

// cd to basePath

if(basePath != null){

Pipeline cdPipeline = runspace.CreatePipeline();

Command cdCommand = new Command("cd");

cdCommand.Parameters.Add("Path", basePath);

cdPipeline.Commands.Add(cdCommand);

cdPipeline.Invoke(); // run the cmdlet

}

// run the "dir" cmdlet (e.g. "dir C:\*\*\*.txt" )

Pipeline dirPipeline = runspace.CreatePipeline();

Command dirCommand = new Command("dir");

dirCommand.Parameters.Add("Path", glob);

dirPipeline.Commands.Add(dirCommand);

Collection dirOutput = dirPipeline.Invoke();

// for each found file

foreach (PSObject psObject in dirOutput) {

PSMemberInfoCollection a = psObject.Properties;

// look for the full path ("FullName")

foreach (PSPropertyInfo psPropertyInfo in psObject.Properties) {

if (psPropertyInfo.Name == "FullName") {

yield return psPropertyInfo.Value.ToString(); // yield it

}

}

}

}

static void Main(string[] args) {

foreach(string path in CmdletDirGlobbing(null,"C:\\*\\*\\*.txt")){

System.Console.WriteLine(path);

}

foreach (string path in CmdletDirGlobbing("C:\\", "*\\*\\*.exe")) {

System.Console.WriteLine(path);

}

Console.ReadKey();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值