在目录中查询已完成的文件(而不是正在复制的文件)
本文关键字:文件 复制 查询 已完成 | 更新日期: 2023-09-27 18:10:16
我尝试使用FileInfo.CreationTime
,但它并不代表复制完成时间。
我正在尝试获取目录中的文件列表。问题是,调用还会返回尚未完成复制的文件。
如果我尝试使用该文件,它会返回一个错误,说明该文件正在使用中。
如何查询完全复制的文件?
如下代码所示。Directory.GetFiles()
返回尚未完成复制的内容。
我的测试文件大小超过200Mb。
if(String.IsNullOrEmpty(strDirectoryPath)){
txtResultPrint.AppendText("ERROR : Wrong Directory Name! ");
}else{
string[] newFiles = Directory.GetFiles(strDirectoryPath,"*.epk");
_epkList.PushNewFileList(newFiles);
if(_epkList.IsNewFileAdded()){
foreach (var fileName in _epkList.GetNewlyAddedFile()){
txtResultPrint.AppendText(DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + " => ");
txtResultPrint.AppendText(fileName + Environment.NewLine);
this.Visible = true;
notifyIconMain.Visible = true;
}
}else{
}
}
如果性能和最佳实践不是很大的问题,那么您可以简单地将失败的文件操作封装在内部范围的try/catch中。
using System.IO;
string[] files = Directory.GetFiles("pathToFiles");
foreach (string file in files) {
FileStream fs = null;
try {
//try to open file for exclusive access
fs = new FileStream(
file,
FileMode.Open,
FileAccess.Read, //we might not have Read/Write privileges
FileShare.None //request exclusive (non-shared) access
);
}
catch (IOException ioe) {
//File is in use by another process, or doesn't exist
}
finally {
if (fs != null)
fs.Close();
}
}
这并不是最好的设计建议,因为你不应该依赖异常处理来处理这类事情,但如果你手头拮据,而且它不是为客户或老板编写的代码,那么在提出或找到更好的解决方案之前,这应该可以正常工作。
您有能力更改复制本身吗?
如果是(并且您可以保证您的程序始终在Windows Vista或更新版本的NTFS上执行(,您可以使用事务性NTFS将副本包装在单个事务中。只有在提交事务后,被复制的文件才会对世界其他地方可见,因此您甚至永远看不到部分复制的文件。
不幸的是,事务性NTFS无法直接从.NET Framework访问-您需要p/Invoke到Win32 APi函数中,如:CreateTransaction
、CommitTransaction
、RollbackTransaction
、CopyFileTransacted
(以及其他*事务性函数(。