【发布时间】:2021-11-24 07:39:22
【问题描述】:
我们有一个流程,人们使用复印机扫描文档并将它们放到我们文件服务器上的某个目录中。然后,我们在 .NET Core 应用程序中有一个每小时一次的服务,它会扫描目录、抓取文件并根据文件名将它们移动到某个目录。问题来了。
代码看起来像这样:
private string MoveFile(string file, string commNumber)
{
var fileName = Path.GetFileName(file);
var baseFileName = Path.GetFileNameWithoutExtension(fileName).Split("-v")[0];
// 1. Check if the file already exists at destination
var existingFileList = luxWebSamContext.Documents.Where(x => EF.Functions.Like(x.DocumentName, "%" + Path.GetFileNameWithoutExtension(baseFileName) + "%")).ToList();
// If the file exists, check for the current version of file
if (existingFileList.Count > 0)
{
var nextVersion = existingFileList.Max(x => x.UploadVersion) + 1;
var extension = Path.GetExtension(fileName);
fileName = baseFileName + "-v" + nextVersion.ToString() + extension;
}
var from = @file;
var to = Path.Combine(@destinationPath, commNumber,fileName);
try
{
log.Info($"------ Moving File! ------ {fileName}");
Directory.CreateDirectory(Path.Combine(@destinationPath, commNumber));
File.Move(from, to, true);
return to;
}
catch (Exception ex)
{
log.Error($"----- Couldn't MOVE FILE: {file} ----- commission number: {commNumber}", ex);
有趣的部分是在try-block,文件移动发生的地方。有时我们会遇到程序抛出以下异常的问题
2021-11-23 17:15:37,960 [60] 错误应用程序 ----- 无法移动文件: \PATH\PATH\PATH\Filename_423489120.pdf ----- 委托号: 05847894 System.IO.IOException:该进程无法访问该文件,因为它正被另一个进程使用。 在 System.IO.FileSystem.MoveFile(字符串 sourceFullPath,字符串 destFullPath,布尔覆盖) 在 System.IO.File.Move(String sourceFileName, String destFileName, Boolean overwrite)
到目前为止一切顺利。我希望文件无法移动后,它仍保留在应该移动的目录中。但事实并非如此。我们昨天下午遇到了这个问题,在我查找文件后,它从目录中消失了。
这是 File.Move() 方法的正常行为吗?
【问题讨论】: