删除文件时Windows服务意外终止问题求助
Windows服务批量删除文件时意外终止,未触发异常捕获
问题现象
这是一个Windows服务,代码中edpAmalgamateBatchList包含2条文件记录。执行foreach循环删除文件时,第一个文件可正常删除,但第二次执行到File.Delete语句时,服务直接终止,且未进入catch块。该代码在本地运行正常,仅服务器环境下出现此问题。
简化版代码
try { foreach (var edpItem in edpAmalgamateBatchList) { NPSLogger.Log.Error("before if..."); if (File.Exists(Path.Combine(edpItem.FILE_LOCATION, edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF"))) { NPSLogger.Log.Debug("inside if"); File.Delete(Path.Combine(edpItem.FILE_LOCATION, edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF")); NPSLogger.Log.Debug(" file deleted."); } } } catch (Exception ex) { NPSLogger.Log.Error("Error - ", ex); return false; }
已尝试的方法
- 在循环间添加1秒
Thread.Sleep,无效果。
更新情况
将sleep改为1分钟后,服务可正常运行。推测是文件被锁定,因此添加了文件锁检测逻辑:若检测到锁定则等待3秒后重试,最多重试5次。但重试逻辑仅执行一次,且IsFileLocked方法未进入异常块,说明文件并未被锁定。
更新后的代码
try { foreach (var edpItem in edpAmalgamateBatchList) { NPSLogger.Log.Debug("before if - " + edpItem.JOB_REFERENCE); NPSLogger.Log.Error("before if..."); if (File.Exists(Path.Combine(edpItem.FILE_LOCATION, edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF"))) { NPSLogger.Log.Debug("inside if"); FileInfo filetoDelete = new FileInfo(Path.Combine(edpItem.FILE_LOCATION, edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF")); for (int tries = 0; IsFileLocked(filetoDelete) && tries < 5; tries++) Thread.Sleep(3000); File.Delete(Path.Combine(edpItem.FILE_LOCATION, edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF")); NPSLogger.Log.Debug(edpItem.JOB_REFERENCE.Replace("\\", "_").Replace("/", "_").Replace(":", "_") + ".PDF" + " file deleted."); } } } catch (Exception ex) { NPSLogger.Log.Error("Error - ", ex); return false; } /// <summary> /// 检测文件是否被锁定 /// </summary> protected virtual bool IsFileLocked(FileInfo file) { FileStream stream = null; NPSLogger.Log.Debug("In IsFileLocked."); try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { NPSLogger.Log.Debug("File is Locked."); // 文件不可用,原因可能是: // 正在被写入 // 被其他线程处理 // 已不存在(已被处理) return true; } finally { if (stream != null) stream.Close(); } NPSLogger.Log.Debug("File is not Locked."); // 文件未被锁定 return false; }
内容的提问来源于stack exchange,提问作者Amin Ansari
相关产品推荐
相关产品推荐

