c# - 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:将复制的文件从指定文件夹粘贴到新创建的文件夹中
解决方案
现在我的问题是如何复制它
简单地说:获取文件名并将其与目标文件夹一起传递给字符串,然后将 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 是如果存在则覆盖。
推荐阅读
- xml - SVG。将文本居中
标签 - java - 更新firebase后,我在android错误消息> zzdk中遇到真实设备错误:找不到密钥集,将生成一个新的
- php - Laravel 查询生成器按天计算行数 SQL db::raw
- azure - 尽管 azure_rm.yml 中存在“cert_validation_mode:ignore”,但使用 Azure Stack 的 Ansible 仍会出现 SSL 验证错误
- mysql - 如何使用 MYSQLWorkbench 从数据库中导出表并在 phpmyadmin 上导入
- javascript - 处理实体组件系统中拖放的碰撞
- mongodb - 使用 docker-compose 卷 mongodb
- vue.js - 禁用并在 vuetify 数据表中显示更多
- javascript - 在 Bootstrap 表中如何在导出到 Excel 功能中显示进度条
- laravel - Laravel JetStream 在资源方法中获取用户的 HasRole