首页 > 解决方案 > C# 将文件夹中的最后一个文件复制到另一个生成的文件夹中

问题描述

我正在尝试从路径中获取最新文件并将其复制,然后将其粘贴到生成的文件夹中。

这是我到目前为止所尝试的:

    // This Method is called if the function/method CopyContent is invoked by the user or a bound event.
// Return true, if this component has to be revalidated!
public bool OnCopyContent(int arg)
{
    // Get latet file from the specificed Folder
    var directory = new DirectoryInfo(@""+sourceFolderPath);
    var myFile = (from f in directory.GetFiles()
            orderby f.LastWriteTime descending
            select f).First();


    // Newly Created Folder Name
    string generatedFolderName = destinationFolderName;


    // Newly Creted Folder Path (i.e C://Users/Desktop) Cretge it on desktop with name "Paste me here " 
    string generatedPathString = System.IO.Path.Combine(destinationFolderPath, generatedFolderName);


    if (!File.Exists(generatedPathString))
        System.IO.Directory.CreateDirectory(generatedPathString);



    // Copy the Latet file to the newly Created Folder on the Desktop
    string destFile = Path.Combine(@""+destinationFolderPath, myFile.Name);



    File.Copy(myFile.FullName, destFile, true);

    return false;
}

我想做的是

1:我有指定的文件夹路径,我想根据时间复制它的最新文件

2:在桌面上创建名为“NewlyAdded”的新文件夹

3:将复制的文件从指定文件夹粘贴到新创建的文件夹中

标签: c#.net

解决方案


现在我的问题是如何复制它

简单地说:获取文件名并将其与目标文件夹一起传递给字符串,然后将 file.FullName 传递给 Copy() 方法,它将被复制。此代码经过测试并有效。

编辑:添加一行以生成文件夹(如果不存在),并将文件复制到其中。

 string newFolder = "NewlyAdded";
            string path = System.IO.Path.Combine(
               Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
               newFolder
            );

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
             }
                    var directory = new DirectoryInfo(@"Sourcd folder");
            var myFile = (from f in directory.GetFiles()
                          orderby f.LastWriteTime descending
                          select f).First();

            string destFile = Path.Combine(path, myFile.Name);
            System.IO.File.Copy(myFile.FullName, destFile, true);

最后一个参数的 true 是如果存在则覆盖。


推荐阅读