C# WinForm如何从文件全路径提取文件名用于MySQL导入去重校验
解决方案
你可以直接使用.NET内置的System.IO.Path.GetFileName()方法,一键提取完整路径中的带后缀文件名,不需要手动拆分字符串处理路径分隔符,兼容性更强。
具体修改方式有两种可选:
方式1:选文件时就拆分存储文件名(推荐)
修改btnSelectNuevo_Click方法,选完文件后同时把完整路径和纯文件名分别存储,后续校验直接取用即可:
private void btnSelectNuevo_Click(object sender, EventArgs e) { if (openFileDialog2.ShowDialog() == DialogResult.OK) { try { string fullPath = openFileDialog2.FileName; // 直接提取带后缀的纯文件名 string fileName = Path.GetFileName(fullPath); txtbox_sel_fich.Text = fullPath; // 纯文件名存在控件的Tag属性里备用,不需要额外声明全局变量 txtbox_sel_fich.Tag = fileName; if (string.IsNullOrEmpty(txtbox_sel_fich.Text)) { MessageBox.Show("file not selected", "return file selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } catch (SecurityException ex) { MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" + $"Details:\n\n{ex.StackTrace}"); } } }
上传校验时直接取预存的纯文件名即可:
private void btnsubir_Click(object sender, EventArgs e) { string reply = ""; // 取之前存在Tag里的纯文件名 string fileName = txtbox_sel_fich.Tag?.ToString() ?? ""; string fullPath = txtbox_sel_fich.Text; if (string.IsNullOrEmpty(fileName)) { MessageBox.Show("请先选择文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (fileName == readLastFile(fileName)) { createLog($"{fileName}: 该文件已导入过,不执行任何操作\n"); MessageBox.Show($"文件 '{fileName}' 已导入过"); } else { // 原有导入逻辑,用fullPath读取文件内容即可 } }
方式2:校验时临时提取文件名
如果不想修改选文件的原有逻辑,直接在上传方法里临时提取即可,你之前注释掉的FileInfo写法也是可行的,两种写法效果完全一致:
private void btnsubir_Click(object sender, EventArgs e) { string reply = ""; string fullPath = textbox_select.Text.ToString(); // 方法A:用Path类提取,代码更简洁 string fileName = Path.GetFileName(fullPath); // 方法B:用你之前注释的FileInfo写法,效果相同 // FileInfo fich = new FileInfo(fullPath); // string fileName = fich.Name; if (fileName == readLastFile(fileName)) { createLog($"{fileName}: 该文件已导入过,不执行任何操作\n"); MessageBox.Show($"文件 '{fileName}' 已导入过"); } else { // 原有导入逻辑 } }
补充优化点:如果你的校验逻辑需要忽略大小写(比如
Hello.xlsx和hello.xlsx视为同一个文件),可以把判断条件改成fileName.Equals(readLastFile(fileName), StringComparison.OrdinalIgnoreCase),避免大小写差异导致的重复导入问题。
内容的提问来源于stack exchange,提问作者Fyah10
相关产品推荐
相关产品推荐

