删除文件名的子路径并创建文件结构
Remove sub-path of File name and create file structure
我有以下 List<String> fileNames
被传递到我的方法,
我想从中删除子路径并创建遗漏的文件结构
string subPath = "C:\temp\test"
List<string> filesIncoming = new List[]{@"C:\temp\test\a.txt", @"C:\temp\test\intest\a.txt"};
string outputDir = "C:\temp3\temp";
输出应该是:
C:\temp3\temp\a.txt
C:\temp3\temp\intest\a.txt
这就是我正在尝试的
foreach (var file in files)
{
var directory = Path.GetDirectoryName(file);
DirectoryInfo source = new DirectoryInfo(directory);
var fileName = Path.GetFileName(file);
var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly?
CreateDirectory(new DirectoryInfo(destDir));
File.Copy(file, Path.Combine(destDir, fileName), true);
}
我认为您应该使用旧的 string.Replace 从传入文件中删除公共基本路径,并将其替换为输出文件的公共基本路径
string subPath = "C:\temp\test"
string outputDir = "C:\temp3\temp";
foreach (var file in files)
{
// Not sure how do you have named these two variables.
string newFilePath = file.Replace(subPath, outputDir);
Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
File.Copy(file, newFilePath, true);
}
我有以下 List<String> fileNames
被传递到我的方法,
我想从中删除子路径并创建遗漏的文件结构
string subPath = "C:\temp\test"
List<string> filesIncoming = new List[]{@"C:\temp\test\a.txt", @"C:\temp\test\intest\a.txt"};
string outputDir = "C:\temp3\temp";
输出应该是:
C:\temp3\temp\a.txt
C:\temp3\temp\intest\a.txt
这就是我正在尝试的
foreach (var file in files)
{
var directory = Path.GetDirectoryName(file);
DirectoryInfo source = new DirectoryInfo(directory);
var fileName = Path.GetFileName(file);
var destDir = Path.Combine(destinatonFilePath, source.Name); //how do I remove sub-path from source.Name and combine the paths properly?
CreateDirectory(new DirectoryInfo(destDir));
File.Copy(file, Path.Combine(destDir, fileName), true);
}
我认为您应该使用旧的 string.Replace 从传入文件中删除公共基本路径,并将其替换为输出文件的公共基本路径
string subPath = "C:\temp\test"
string outputDir = "C:\temp3\temp";
foreach (var file in files)
{
// Not sure how do you have named these two variables.
string newFilePath = file.Replace(subPath, outputDir);
Directory.CreateDirectory(Path.GetDirectoryName(newFilePath));
File.Copy(file, newFilePath, true);
}