【问题标题】:Delete files, copy the same named files from another folder C#删除文件,从另一个文件夹 C# 复制相同命名的文件
【发布时间】:2015-04-05 14:30:06
【问题描述】:

我在 Windows 窗体应用程序中有几个问题。到目前为止,我已经设法遍历一个文件夹并在文本框中显示结果。一旦这些都返回,用户可以检查结果,并且可以使用以下方法删除错误文件;

private void button2_Click(object sender, EventArgs e)
{
    foreach (string file in Directory.GetFiles(@"\\" + textBox1.Text + @"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
    {
        File.Delete(file);
    }
}

在删除错误文件后,我现在要做的是从备份文件夹中复制相同的文件(文件名的唯一区别是文件扩展名)我正在使用单独的按钮来执行此操作。对于这最后一步的任何帮助,我们将不胜感激。

【问题讨论】:

  • 为什么不直接移动和覆盖文件?.. 也有大量关于这方面的研究材料
  • 您好,感谢您的回复。错误文件并不总是需要在文件夹中替换。有时只需要删除它们。

标签: c# replace copy


【解决方案1】:

使用Path类获取不带扩展名的文件名,组合路径等,例如:

StringCollection filesToBeReplaced = new StringCollection();

private void button2_Click(object sender, EventArgs e)
{
foreach (string file in Directory.GetFiles(@"\\" + textBox1.Text +      @"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))
{
  //Now you have file names without extension        
  filesToBeReplaced.Add(Path.GetFileNameWithoutExtension (file));
      File.Delete(file);
  }
}
private void CopyGoodFilesFromSource()
{
  foreach(string fileName in filesToBeReplaced)
  {
     string sourceFilePath = Path.Combine("YOUR FOLDER FOR GOOD FILES", 
Path.ChangeExtension(fileName,"Your Extension")) ;
      string destinationPath = Path.Combine("Destination Folder",
Path.ChangeExtension(fileName, "Your Extension in destination folder");

     File.Copy(sourceFilePath , destinationPath, true);
  }
}

【讨论】:

  • 很高兴我能帮上忙 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2013-05-21
  • 2020-05-24
  • 1970-01-01
  • 2023-01-14
  • 2015-05-10
相关资源
最近更新 更多