C# 复制文件排除一个文件夹
基本上,我想复制一个文件夹中的所有内容,但不包括一个文件夹,该文件夹恰好是存储程序日志的地方。(我知道我可以把日志存储在别处,但我有我的理由)。到目前为止,我已经:C# 复制文件排除一个文件夹,c#,C#,基本上,我想复制一个文件夹中的所有内容,但不包括一个文件夹,该文件夹恰好是存储程序日志的地方。(我知道我可以把日志存储在别处,但我有我的理由)。到目前为止,我已经: private void btnCopyFiles_Click(object sender, EventArgs e) { try { //Copy all the files foreach (string newPath in Directo
private void btnCopyFiles_Click(object sender, EventArgs e)
{
try
{
//Copy all the files
foreach (string newPath in Directory.GetFiles(@"\\xxx\yyy", "*.*",
SearchOption.AllDirectories)
.Where(p => p != Logging.fullLoggingPath))
File.Copy(newPath, newPath.Replace(@"\\xxx\yyy", @"C:\bbb"));
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("All necessary files copied to C:\\bbb", w);
}
}
catch
{
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("Error copying files, make sure you have permissions to access the drive and write to the folder.", w);
}
}
}
如何修改此选项以排除
\\xxx\yyy
中的一个特定文件夹检查文件夹名称并跳过它
foreach (string newPath in Directory.GetFiles(@"\\xxx\yyy", "*.*", SearchOption.AllDirectories))
{
String currentFolder = "";
int lastSlash = newPath.LastIndexOf("\\");
int secondLastSlash = newPath.Substring(0, newPath.Length - (newPath.Length - lastSlash)).LastIndexOf("\\")+1;
currentFolder = newPath.Substring(secondLastSlash,(lastSlash-secondLastSlash))
If(!currentFolder.Equals(NameOfFolderNotToInclude))
File.Copy(newPath, newPath.Replace(@"\\xxx\yyy", @"C:\bbb"), true);
}
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("All necessary files copied to C:\\bbb", w);
}
lastSlash变量是字符串中最后一个\的位置,表示实际文件后面的文本。然后,我们创建一个子字符串,删除文件路径字符串中最后一个\之后的所有内容。这为我们提供了到文件夹的路径。然后,我们利用子字符串查找下一个\以便只提取特定文件夹
所以在C:\users\someone\desktop\test.txt这样的路径中
lastSlash将指示\before test.txt
我们使用它创建一个子字符串,该子字符串等于C:\users\someone\desktop
然后,我们使用相同的方法查找此路径中的最后一个\
我们将其组合在一起,以提取桌面的文件夹
您可以使用Jim Mischel的建议,因为它更易于用户使用和阅读。下面是一个例子
foreach (string newPath in Directory.GetFiles(@"\\xxx\yyy", "*.*", SearchOption.AllDirectories))
{
if(Path.GetDirectory(newPath) != PathToExclude)
File.Copy(newPath, newPath.Replace(@"\\xxx\yyy", @"C:\bbb"), true);
}
using (StreamWriter w = File.AppendText(Logging.fullLoggingPath))
{
Logging.Log("All necessary files copied to C:\\bbb", w);
}
在循环中,只需添加一个条件即可排除该目录
If (Path.GetDirectory(newPath) == PathToExclude)
Continue;
您还可以使用“难道不必从文件名中提取目录吗?”“Except”需要另一个IEnumerable。我认为Where更合理,尽管两者都工作正常。@FrK请捕获抛出的异常并报告其消息是什么file.Copy有一个重载,您可以通过该重载强制覆盖现有文件:file.Copy(…,…,true);但是GetFiles返回文件名,而不是目录名。您必须从完整文件名中提取目录名,以便排除该目录中的所有文件。@JimMischel,如文档所述:“GetFiles返回指定目录中的文件名(包括其路径)。()您不需要提取任何内容。请参阅udpdated代码,了解它为什么总是“捕获”文件名的原因我已经更新了代码,显示了如何获取文件所在的文件夹,尽管Jim Mischel有更好的方法获取文件夹;我会看你的更新code@FrK发布正在抛出的异常它抛出了什么异常?该异常基于文件已经存在,我可以在此命令上设置强制覆盖吗?
If (Path.GetDirectory(newPath) == PathToExclude)
Continue;