[英]C# copy last file from a folder into another generated folder
我正在尝试从路径中获取最新文件并将其复制,然后将其粘贴到生成的文件夹中。
这是我到目前为止尝试过的:
// 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:将复制的文件从指定的文件夹粘贴到新创建的文件夹
现在我的问题是如何复制它
简单:将文件名与目标文件夹一起传递给字符串,然后将文件全名传递给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是覆盖(如果存在)。
查看文档,第一个参数是原始文件的路径。
https://msdn.microsoft.com/en-us/library/9706cfs5(v=vs.110).aspx
我正在尝试复制它,但是我现在不确定如何传递
您使用原始文件的文件路径,而不是FileInfo本身!
像这样:
var directory = new DirectoryInfo(@"C:\");
FileInfo myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
string filePath = myFile.FullName;
您将使用此filePath变量,而不是当前使用的FileInfo实例。
通过使用二进制写入将文件写入特定目录后
可能对您有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.