C#如何移除文件路径字符串最后一个斜杠后的多余内容
解决方案
核心问题说明
手动通过字符串截断处理路径的方式兼容性差,无法适配Windows系统下的反斜杠\路径格式,也无法处理末尾带斜杠等边缘场景。.NET类库已经提供了专门处理路径的工具类,无需自己实现字符串操作逻辑。
修复步骤
- 提取文件夹路径使用
System.IO.Path.GetDirectoryName()方法,可自动适配不同系统的路径分隔符,正确从带文件名的完整路径中提取所属文件夹路径 - 拼接输出文件路径使用
Path.Combine()方法,自动处理路径之间的分隔符,避免出现缺少斜杠导致路径拼接错误的问题 using代码块会自动释放资源,无需手动调用Close()和Dispose()方法,可删除冗余代码
修改后代码
private void RecieptDisplayed_TextChanged(object sender, EventArgs e) { try { // 自动从路径中提取文件夹路径,兼容正反斜杠 string folderPath = Path.GetDirectoryName(RecieptSelect.Text); string[] fileAry = Directory.GetFiles(folderPath); MessageBox.Show("Reciepts being processed : " + fileAry.Length); // 自动拼接路径,避免分隔符缺失问题 string outputPath = Path.Combine(savefileas.Text, "RecieptsCombined.txt"); using (TextWriter tw = new StreamWriter(outputPath, true)) { foreach (string filePath in fileAry) { using (TextReader tr = new StreamReader(filePath)) { tw.WriteLine("Reciept for: " + filePath + tr.ReadToEnd()); } MessageBox.Show("File Processed : " + filePath); } } } // 补充异常捕获逻辑避免程序直接崩溃 catch (Exception ex) { MessageBox.Show("处理出错:" + ex.Message); } }
额外优化建议
- 如果仅需要选择目标文件夹,可改用
FolderBrowserDialog控件,选完直接返回纯净的文件夹路径,不需要额外做路径截取 - 可对输入的路径做非空校验,避免空路径触发运行时异常
内容的提问来源于stack exchange,提问作者user17019895
相关产品推荐
相关产品推荐

