创建备份C#的日志

时间:2017-05-11 07:48:04

标签: c# logging backup

所以我想记录备份文件时会发生什么,但我不确定如何使其适用于子目录中的文件。 现在我有这个代码适用于所选目录中的所有文件,但不适用于子目录文件

private void LogBackup(string sourceDirName, string destDirName)
    {
        List<string> lines = new List<string>();
        string logDestination = this.tbox_LogFiles.Text;
        string dateString = DateTime.Now.ToString("MM-dd-yyyy_H.mm.ss");

        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        DirectoryInfo[] dirs = dir.GetDirectories();

        lines.Add("FILES TO COPY:");
        lines.Add("--------------");

        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files
            .Where(f => !extensionsToSkip.Contains(f.Extension) && !filesToSkip.Contains(f.FullName)).ToList())
        {
            string desttemppath = Path.Combine(destDirName, file.Name);
            string sourcetemppath = Path.Combine(sourceDirName, file.Name);
            lines.Add("SOURCE FILE:");
            lines.Add(sourcetemppath);
            lines.Add("DESTINATION FILE:");
            lines.Add(desttemppath);
            lines.Add("");
        }

        foreach (DirectoryInfo subdir in dirs
            .Where(f => !foldersToSkip.Contains(f.FullName)))
        {
            //NOT SURE WHAT TO WRITE HERE
        }

        using (StreamWriter writer = new StreamWriter(logDestination + @"\LOG " + dateString + ".txt"))
        {
            foreach (string line in lines)
            {
                writer.WriteLine(line);
            }
        }

    }

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

包含SearchOption.AllDirectories,您将获得所有子目录:

DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories("*", SearchOption.AllDirectories);

当你现在遍历这些目录时,你将拥有第一级子目录,并且每个目录只获取它包含的文件

foreach (DirectoryInfo subdir in dirs)
{
    FileInfo[] files = subdir.GetFiles();

    ......