簡體   English   中英

從C#中的最新子目錄復制文件

[英]Copy files from the latest sub directory in c#

我已經為此苦苦掙扎了幾天,無法解決。

我需要從目錄中最后一個創建的子目錄中復制文件,該子目錄也有一些子目錄,在進入這些文件之前,必須先對其進行導航,這就是問題所在。

希望我說得很清楚,在此我舉一個下面目錄的例子,在此先感謝您的幫助。

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

以粗體突出顯示的數字是我需要找到最新目錄的子目錄,並且在services文件夾中是我需要從中復制文件的位置。

這是我嘗試過的代碼

字符串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);
                    }
                }
            }

假設LongTerm目錄存儲在某處(例如Application-Settings),因此該目錄是已知的:

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

具有SearchOption.AllDirectories Directory.EnumerateDirectories遞歸枚舉所有目錄。 具有目錄名稱編號的Enumerable.OrderByDescending將按數字順序對其進行排序,並按最高順序排序(因此49之前為50,99之前為100)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM