You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现匹配recetaBox文本文件名从指定文件夹复制文件的功能问题

功能实现修改方案
  • 先获取recetaBox的输入值,自动去除前后空白字符
  • 遍历源目录文件时,匹配规则为「文件名(不含后缀)与输入值完全一致」,不限制文件后缀类型
  • 新增匹配结果校验,未找到匹配文件时弹出指定警告
  • 修复原代码中File.Copy目标路径错误的问题(原代码目标路径仅写了文件夹,会触发运行报错)

修改后完整代码如下:

private void cargarButton_Click(object sender, EventArgs e)
{
    if (serieBox.Text == string.Empty)
    {
        SerieWin openForm = new SerieWin();
        openForm.ShowDialog();
    }
    else
    {
        try
        {
            string dircopyFrom = @"C:\From\";
            string dircopyTo = @"C:\To\";
            // 取recetaBox输入的目标文件名,去除前后空格
            string targetFileName = recetaBox.Text.Trim();
            // 标记是否找到匹配文件
            bool fileFound = false;
            string[] files = Directory.GetFiles(dircopyFrom);

            foreach (string file1 in files)
            {
                // 取不带后缀的文件名
                string fileNameWithoutExt = Path.GetFileNameWithoutExtension(file1);
                // 匹配文件名(如需不区分大小写可加StringComparison.OrdinalIgnoreCase参数)
                if (fileNameWithoutExt == targetFileName)
                {
                    string destPath = Path.Combine(dircopyTo, Path.GetFileName(file1));
                    File.Copy(file1, destPath, true);
                    fileFound = true;
                }
            }
            
            // 未找到匹配文件时弹出警告
            if (!fileFound)
            {
                MessageBox.Show("file not found");
            }
        }
        catch (Exception ex)
        {
            // 可根据需要添加异常处理逻辑,比如弹错误提示
            MessageBox.Show($"操作出错:{ex.Message}");
        }
    }
}

可选调整说明

  • 如果需要支持不区分大小写匹配,可将判断条件改为fileNameWithoutExt.Equals(targetFileName, StringComparison.OrdinalIgnoreCase)
  • 如果需要匹配包含输入值的文件名而非完全匹配,可将判断条件改为fileNameWithoutExt.Contains(targetFileName)

内容的提问来源于stack exchange,提问作者fjleon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:15:05