c# - 在文件路径中复制文件夹结构的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/438321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# - Function to replicate the folder structure in the file path
提问by renegadeMind
I need a simple function which will take a FileInfo and a destination_directory_name as input, get the file path from the fileinfo and replicate it in the destination_directory_name passed as the second parameter.
我需要一个简单的函数,它将一个 FileInfo 和一个 destination_directory_name 作为输入,从 fileinfo 获取文件路径并将其复制到作为第二个参数传递的 destination_directory_name 中。
for ex. filepath is "d:\recordings\location1\client1\job1\file1.ext the function should create the directories in the destination_directory_name if they dont exist and copy the file after creating the directories.
例如。文件路径是“d:\recordings\location1\client1\job1\file1.ext,如果destination_directory_name 目录不存在,该函数应该创建目录,并在创建目录后复制文件。
采纳答案by M4N
I'm using the following method for that purpose:
为此,我使用了以下方法:
public static void CreateDirectory(DirectoryInfo directory)
{
if (!directory.Parent.Exists)
CreateDirectory(directory.Parent);
directory.Create();
}
Use it in this way:
以这种方式使用它:
// path is your file path
string directory = Path.GetDirectoryName(path);
CreateDirectory(new DirectoryInfo(directory));
回答by M4N
System.IO.Directory.CreateDirectory can be used to create the final directory, it will also automatically create all folders in the path if they do not exist.
System.IO.Directory.CreateDirectory 可用于创建最终目录,如果路径中的所有文件夹不存在,它也会自动创建。
//Will create all three directories (if they do not already exist).
System.IO.Directory.CreateDirectory("C:\First\Second\Third")
回答by blak3r
Based on @NTDLS's answer here's a method that will replicate source to destination. It handles case where source is a file or a folder. Function name kind of stinks... lemme know if you think of a better one.
基于@NTDLS 的回答,这里有一种将源复制到目标的方法。它处理源是文件或文件夹的情况。函数名称有点臭......让我知道你是否想到了一个更好的。
/// <summary>
/// Copies the source to the dest. Creating any neccessary folders in the destination path as neccessary.
///
/// For example:
/// Directory Example:
/// pSource = C:\somedir\conf and pDest=C:\somedir\backups\USER_TIMESTAMP\somedir\conf
/// all files\folders under source will be replicated to destination and any paths in between will be created.
/// </summary>
/// <param name="pSource">path to file or directory that you want to copy from</param>
/// <param name="pDest">path to file or directory that you want to copy to</param>
/// <param name="pOverwriteDest">if true, files/directories in pDest will be overwritten.</param>
public static void FileCopyWithReplicate(string pSource, string pDest, bool pOverwriteDest)
{
string destDirectory = Path.GetDirectoryName(pDest);
System.IO.Directory.CreateDirectory(destDirectory);
if (Directory.Exists(pSource))
{
DirectoryCopy(pSource, pDest,pOverwriteDest);
}
else
{
File.Copy(pSource, pDest, pOverwriteDest);
}
}
// From MSDN Aricle "How to: Copy Directories"
// Link: http://msdn.microsoft.com/en-us/library/bb762914.aspx
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, true);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
回答by Jason Ausborn
Similar to the question, I am copying a folder structure from one destination and duplicating it to another. Sorry for posting to an old thread, but it may be useful for someone that ends up here.
与问题类似,我正在从一个目的地复制文件夹结构并将其复制到另一个目的地。很抱歉张贴到旧线程,但它可能对最终到达这里的人有用。
Let's assume that we have an application that is standalone, and we need to copy the folder structure from an Input folder to an Output folder. The Input folder and Output folder is in the root directory of our application.
假设我们有一个独立的应用程序,我们需要将文件夹结构从 Input 文件夹复制到 Output 文件夹。Input 文件夹和 Output 文件夹位于我们应用程序的根目录中。
We can make a DirectoryInfo for the Input folder (structure we want to copy) like this:
我们可以为 Input 文件夹(我们要复制的结构)创建一个 DirectoryInfo,如下所示:
DirectoryInfo dirInput = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\Input\");
Our output folder location can be stored in a string.
我们的输出文件夹位置可以存储在一个字符串中。
string dirOutput = AppDomain.CurrentDomain.BaseDirectory + "\Output\";
This recursive method should handle the rest for us.
这个递归方法应该为我们处理剩下的事情。
public static void ProcessDirectories(DirectoryInfo dirInput, string dirOutput)
{
string dirOutputfix = String.Empty;
foreach (DirectoryInfo di in dirInput.GetDirectories())
{
dirOutputfix = dirOutput + "\" + di.Name);
if (!Directory.Exists(dirOutputfix))
{
try
{
Directory.CreateDirectory(dirOutputfix);
}
catch(Exception e)
{
throw (e);
}
}
ProcessDirectories(di, dirOutputfix);
}
}
This method can be easily modified to handle files also, but I designed it with only folders in mind for my project.
这个方法也可以很容易地修改来处理文件,但我设计它时只考虑了我的项目的文件夹。
Now we just call the method with our dirInput and dirOutput.
现在我们只需使用 dirInput 和 dirOutput 调用该方法。
ProcessDirectories(dirInput, dirOutput);