C#将最后一个文件从一个文件夹复制到另一个生成的文件夹中
我试图从路径中获取最新文件并复制它,然后将其粘贴到生成的文件夹中 这就是我迄今为止所尝试的:C#将最后一个文件从一个文件夹复制到另一个生成的文件夹中,c#,.net,C#,.net,我试图从路径中获取最新文件并复制它,然后将其粘贴到生成的文件夹中 这就是我迄今为止所尝试的: // 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) {
// 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:将指定文件夹中复制的文件粘贴到新创建的文件夹中查看文档,第一个参数是原始文件的路径 我试图复制它,但我不知道现在如何传递它 您使用的是原始文件的文件路径,而不是文件信息本身 像这样:
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实例。- 若你们不能复制字符串文件,那个么打开你们当前想要以二进制读取(rb)格式复制的文件,并将其存储在变量中
- 在使用二进制写入将该文件写入特定目录之后 也许它会对你有所帮助
- 现在我的问题是如何复制它
简单地说:获取文件名并将其与目标文件夹一起传递到字符串,
然后将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是覆盖(如果存在) 这是怎么回事?我不希望它复制整个文件夹,我希望它只复制最后一个文件我got@David编辑-现在明白了吗?请让我测试一下。非常感谢。我会检查一下然后告诉你当我尝试的时候,我得到一个异常,上面写着“目标是一个目录而不是一个文件”@David它很明显是一个随机文件名….`字符串文件名=System.IO.Path.GetRandomFileName();`从你原来的帖子。Lol:)字符串destFile=Path.Combine(@“区分文件夹”,myFile.Name);Distination文件夹是一个生成的FolderOk将其名称传递给方法,我真的没有发现这里的问题,我不确定这是否适用于genrated文件夹。我已经更新了我的代码,请检查我如何传递生成文件夹的名称?我真的不懂你的代码!好的,我会问不同的问题,你会在哪里生成那个文件夹?是随机的吗?请告诉我你想要生成文件夹的方法,这样我可以帮你更多。对不起,请检查我编辑的问题,我已经清除了可能重复的问题,你的问题到底是什么?您的代码乍一看很好-您有什么错误或出了什么问题?