c# - 复制文件路径中的文件夹结构的函数

发布于 2024-07-10 22:17:30 字数 216 浏览 15 评论 0原文

我需要一个简单的函数,它将接受 FileInfo 和目的地目录名称作为输入,从文件信息中获取文件路径并将其复制到作为第二个参数传递的目的地目录名称中。

对于前。 文件路径为“d:\recordings\location1\client1\job1\file1.ext 该函数应该在destination_directory_name 中创建目录(如果它们不存在),并在创建目录后复制文件。

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

山田美奈子 2024-07-17 22:17:30

System.IO.Directory.CreateDirectory可用于创建最终目录,如果路径中不存在,它也会自动创建所有文件夹。

//Will create all three directories (if they do not already exist).
System.IO.Directory.CreateDirectory("C:\\First\\Second\\Third")

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.

//Will create all three directories (if they do not already exist).
System.IO.Directory.CreateDirectory("C:\\First\\Second\\Third")
巾帼英雄 2024-07-17 22:17:30

我为此目的使用以下方法:

public static void CreateDirectory(DirectoryInfo directory)
{
    if (!directory.Parent.Exists)
        CreateDirectory(directory.Parent);
    directory.Create();
}

以这种方式使用它:

// path is your file path
string directory = Path.GetDirectoryName(path);
CreateDirectory(new DirectoryInfo(directory));

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));
压抑⊿情绪 2024-07-17 22:17:30

根据 @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);
            }
        }
    }

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.

    /// <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);
            }
        }
    }
£冰雨忧蓝° 2024-07-17 22:17:30

与问题类似,我正在从一个目的地复制文件夹结构并将其复制到另一个目的地。 很抱歉发布到旧线程,但它可能对最终到达这里的人有用。

假设我们有一个独立的应用程序,并且需要将文件夹结构从输入文件夹复制到输出文件夹。 输入文件夹和输出文件夹位于我们应用程序的根目录中。

我们可以为输入文件夹(我们要复制的结构)创建一个 DirectoryInfo,如下所示:

DirectoryInfo dirInput = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\Input\\");

我们的输出文件夹位置可以存储在字符串中。

string dirOutput = AppDomain.CurrentDomain.BaseDirectory + "\\Output\\";

这个递归方法应该为我们处理剩下的事情。

    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);
        }
    }

这种方法可以很容易地修改来处理文件,但我在设计它时只考虑了我的项目的文件夹。

现在我们只需使用 dirInput 和 dirOutput 调用该方法。

ProcessDirectories(dirInput, dirOutput); 

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.

We can make a DirectoryInfo for the Input folder (structure we want to copy) like this:

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.

ProcessDirectories(dirInput, dirOutput); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文