【问题标题】:C# winforms get nth folders from pathC# winforms 从路径中获取第 n 个文件夹
【发布时间】:2020-04-06 19:53:28
【问题描述】:

我有一个可用的绝对路径。说:C:/Program/CoreFiles/Folder1/Folder2/File.txt

我需要将该文件复制到C:/Program/Projects/ProjectName/,但它需要保持Folder1/Folder2/File.txt 不变。所以最终结果应该是C:/Program/Projects/ProjectName/Folder1/Folder2/File.txt

我第一次尝试解决这个问题是尝试获取 2 个绝对路径之间的相对路径。发现 Path.GetRelativePath(string, string) 显然没有帮助,因为它不适用于 WinForms。无论如何它都会搞砸,因为最终结果将是C:/Program/Projects/ProjectName/CoreFiles/Folder1/Folder2/File.txt

目标目录是空的,我事先不知道要复制的相对路径,除非以某种方式从绝对路径中获取该信息。由于File.Copy 不会创建尚不存在的文件夹,我需要先创建它们。那么如何从绝对路径中获取从CoreFiles 目录指向文件的路径呢?

我能想到的唯一可行的解​​决方案是使用正则表达式将路径字符串中的CoreFiles 替换为Projects/ProjectName 并使用它。但这在某种程度上似乎是错误的方法。

【问题讨论】:

  • Directory.CreateDirectory() 确实构建了嵌套路径。您可以使用 Uri 类并获取 Segments,跳过目录名称,直到找到要从 (CoreFiles) 开始的目录名称。然后使用Path.Combine重建目标路径。

标签: c# winforms path


【解决方案1】:

因为你不能使用Path.GetRelativePath。我建议查看另一个描述如何自己执行此操作的答案。 喜欢这里...

使用该答案中的方法,您可以完成其余任务,如下所示。

string sourcePath = "C:/Program/CoreFiles/Folder1/Folder2/File.txt";
string sourceRoot = "C:/Program/CoreFiles/";
string destinationRoot = "C:/Program/Projects/ProjectName/";

// Use built-in .NET Path.GetRelativePath if you can. Otherwise use a custom function. Like here https://stackoverflow.com/a/340454/1812944
string relativePath = MakeRelativePath(sourceRoot, sourcePath);

// Combine the paths, and make the directory separators all the same. 
string destinationPath = Path.GetFullPath(Path.Combine(destinationRoot, relativePath));

// Create nested folder structure for your files. 
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));

// Copy the file over. 
File.Copy(sourcePath, destinationPath);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2013-06-16
    相关资源
    最近更新 更多