【问题标题】:Copy files from the latest sub directory in c#从c#中的最新子目录复制文件
【发布时间】:2012-12-12 20:13:48
【问题描述】:

我已经为此苦苦挣扎了几天,无法弄清楚。

我需要从目录中最后创建的子目录中复制文件,子目录还有一些子目录可以在我找到文件之前导航,这就是问题所在。

我希望我说清楚了,我将在下面给出一个目录示例,在此先感谢您的帮助。

C:\ProgramFiles\BuildOutput\mmh\LongTerm\**49**\release\MarketMessageHandler\Service\

以粗体突出显示的数字是我需要找到最新的子目录,在服务文件夹中是我需要从中复制文件的位置...

这是我尝试过的代码

string sourceDir = @"\sttbedbsd001\BuildOutput\mmh\LongTerm\51\release\MarketMessageHandler\Service"; 字符串目标 = @"C:\Users\gwessels\Desktop\test\";

            string[] sDirFiles = Directory.GetFiles(sourceDir, "*", SearchOption.TopDirectoryOnly);

            string targetDir;

            if (sDirFiles.Length > 0)
            {
                foreach (string file in sDirFiles)
                {
                    string[] splitFile = file.Split('\\');
                    string copyFile = Path.GetFileName(file);
                    string source = sourceDir + "\\" + copyFile;

                    targetDir = target + copyFile;

                    try
                    {
                        if (File.Exists(targetDir))
                        {
                            File.Delete(targetDir);
                            File.Copy(source, targetDir);
                        }

                        else
                        {
                            File.Copy(source, targetDir);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }

【问题讨论】:

  • 定义“最新的”——你的意思是最高的数字吗?还是最近的创建日期?
  • 你使用的根目录是什么?它是您存储在某处的静态目录还是您如何确定它?
  • 该目录存储在本地服务器上,最新的我的意思是每次有一个新版本时都会创建一个新文件夹,其中包含所有相同的子目录 49 50 51 等

标签: c#


【解决方案1】:

假设LongTerm 目录是已知的,因为它存储在某处(例如应用程序设置):

string longTermDirectory = Properties.Settings.Default.LongTermDirectory;
DirectoryInfo dir = new DirectoryInfo(longTermDirectory);
dir.Create(); // does nothing if it already exists
int Number = int.MinValue;
DirectoryInfo latestFolder = dir.EnumerateDirectories("*.*", SearchOption.AllDirectories)
    .Where(d => int.TryParse(d.Name, out Number))
    .Select(Directory => new { Directory, Number })
    .OrderByDescending(x => x.Number)
    .Select(x => x.Directory)
    .First();

Directory.EnumerateDirectoriesSearchOption.AllDirectories 递归枚举所有目录。 Enumerable.OrderByDescending 带有目录名称的编号将按数字顺序排列它们,最高的在前(因此 50 在 49 之前,100 在 99 之前)。

【讨论】:

  • 谢谢蒂姆,我会试试的。
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 2020-02-15
  • 2014-04-03
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多