【问题标题】:Using Wildcard in C# to get the string of a dynamic generated file?在 C# 中使用通配符获取动态生成文件的字符串?
【发布时间】:2017-01-13 17:37:00
【问题描述】:

这是我在堆栈溢出中的第一个问题。 这是我目前的问题和我希望解决的问题

我有这个每天生成的动态生成的文件

"EDIOut5_20170112_063449.csv"

我想把它移到另一个目录。 我目前正在使用System.IO.File.Move()

我的主要问题是当我尝试调用字符串时,这部分代码是随机生成的

"063449"

就这样结束了。

 string fileName = "EDIOut"+ dayOfWeekplus + "_" + shortDate + "_" + "063449" + ".csv";

问题是。我可以在 C# 中使用通配符来替换代码中随机生成的部分吗?

谢谢!

【问题讨论】:

    标签: c# string wildcard


    【解决方案1】:

    您可能希望将任务分为 2 个步骤...

    1. 文件文件使用Directory.GetFiles() 查找匹配特定模式的文件(注意* 字符是通配符)
    2. 使用File.Move()移动找到的文件

    示例代码:

    // use wildcard pattern containing *
    string pattern = "EDIOut"+ dayOfWeekplus + "_" + shortDate + "_" + "*" + ".csv"
    // get list of files matching pattern
    string[] files = System.IO.Directory.GetFiles(@"C:\your\path\here\", pattern);
    // move found files to new location
    for (int i = 0; i < files.Length; i++)
    {
        System.IO.File.Move(files[i], @"c:\new\path\" + Path.GetFileName(files[i]));
    }
    

    【讨论】:

    • 领先我 6 分钟!我也打算推荐正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多