【问题标题】:Copy File to another Folder Structure将文件复制到另一个文件夹结构
【发布时间】:2016-06-17 09:59:01
【问题描述】:

我目前正在尝试创建一个程序,该程序应将文件夹结构复制到目录中。

这是一个示例:
C:\test1\folder\folder\file.txt 应该以 C:\test2\folder\folder\file.txt 结尾

我有一个 List<FileSystemInfo 用于源文件夹,现在我需要复制文件并创建文件夹,如示例中所示。

由于文件名限制为 260 个字符,我想在没有路径名字符串的情况下执行此操作。

我有这个代码来复制带有路径名的文件:

string destFile = BackupOptions.DestinationFolder + sourceFileInfo.FullName;
string destParent = Directory.GetParent(destFile).FullName;
string backupFolder = destParent + @ "\backupFolder";
try {
 while (!Directory.Exists(destParent)) {
  if (!Directory.Exists(destParent)) {
   Directory.CreateDirectory(destParent);
  }
 }
 FileAttributes fileAttributes = sourceFileInfo.Attributes;
 if ((fileAttributes & FileAttributes.Directory) == FileAttributes.Directory) {
  Directory.CreateDirectory(destFile);
 } else {
  FileInfo file = (FileInfo) sourceFileInfo;
  file.CopyTo(destFile, true);
 }
} catch (Exception e) {
 Console.Write(e.Message);
 return false;
}

有人知道如何仅使用该文件/对象的 FileSystemInfo-Object 来复制文件/目录吗?

【问题讨论】:

    标签: c# file backup filesysteminfo


    【解决方案1】:

    我认为目前没有任何 .NET IO 类支持长路径。没有办法解决我所知道的。在 .NET 4.0 时间框架内,该团队曾公开尝试添加该内容,但从未成功。

    使用搜索引擎查找添加此内容的库。该库在内部使用 PInvoke(当然您可以在不太方便的情况下直接使用它)。我认为 AlphaFS 是一个众所周知的名字。

    您可以简化代码:Directory.CreateDirectory 同时创建多个级别,并且在目录已经存在时不会失败。这几乎总是您需要的。

    然后将它与对象的父文件夹字符串一起使用并在目标文件夹中创建目录

    不是 100% 确定你的意思,但很可能是对的 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多