查询目录以查找完整的文件(不是正在复制的文件)

时间:2011-10-04 00:59:43

标签: c# .net

我尝试使用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{

                }
            }

2 个答案:

答案 0 :(得分:2)

如果性能和最佳实践不是很大的问题,那么您可以简单地将失败的文件操作包装在内部范围的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();
     }
 }

这不是最好的设计建议,因为你不应该依赖异常处理来做这类事情,但是如果你处在紧张状态并且它不是客户端或老板的代码那么这应该是工作正常,直到建议或找到更好的解决方案。

答案 1 :(得分:0)

你有能力改变你自己的复制吗?

如果是(并且如果您可以保证您的程序将始终在Windows Vista或更高版本的NTFS上执行),则可以使用Transactional NTFS将副本包装在单个事务中。正在复制的文件只有在您提交交易之后才会显示给世界其他地方,因此您甚至不会看到部分复制的文件。

不幸的是,无法直接从.NET Framework访问事务性NTFS - 您需要P / Invoke到Win32 APi函数,例如:CreateTransactionCommitTransactionRollbackTransaction,{{ 1}}(以及其他*转换函数)。