После этого над которым ведется работа, создается текстовый файл с тем же именем, что и у zip-файла, который после успешного распаковывания удаляется. Текстовый файл записывается с сообщением об ошибке, поэтому они хотят сохранить его, но переместить в случае ошибки. Я могу переместить zip-файл без проблем. Однако текстовый файл заблокирован, и я не могу разблокировать его программно. Похоже, что файл заблокирован другим процессом, и все попытки разблокировать его не увенчались успехом. Если я попытаюсь переместить файл вручную, мне будет отказано в доступе, и мне потребуются права администратора, но ошибка, зарегистрированная в файле, который я перемещаю, не указывает на эту проблему.
Попытки:
Я попытался разблокировать файл, открыв его с помощью FileStream с помощью FileShare.ReadWrite, ожидая, что это снимет все блокировки.
Я также использовал специальные вспомогательные методы для проверки и разблокировки файла. файл, но кажется, что файл остается заблокировано, и я не могу его переместить.
Любая помощь приветствуется — спасибо!
Это код:
Код: Выделить всё
private void MoveToFailureFolder(FileInfo file, StreamWriter sw, string exceptionDetails)
{
try
{
string failureFolderPath = Config.Get("FailureFolder");
if (string.IsNullOrWhiteSpace(failureFolderPath))
{
log.Info("Failure Folder path is not configured");
throw new ConfigurationErrorsException("Failure Folder path is not configured");
}
// Construct the destination path in the FailureFolder
string destinationPath = Path.Combine(failureFolderPath, file.Name);
// Log the exception to the "Running" file
sw.WriteLineTime(exceptionDetails);
// Move the corrupt file to the Failure folder
File.Move(file.FullName, destinationPath);
log.Info($"File moved to Failure: {file.Name}");
sw.WriteLineTime($"Offending file moved to Failure: {file.Name}");
string runningFileName = Path.Combine(file.DirectoryName, Path.GetFileNameWithoutExtension(file.Name) + Config.Get("RunningFileName"));
// Check if the associated "Running" file exists and move it if it does
if (File.Exists(runningFileName))
{
// Move the "Running" file to the failure folder
string runningDestinationPath = Path.Combine(failureFolderPath, Path.GetFileName(runningFileName));
File.Move(runningFileName, runningDestinationPath);
log.Info($"Running file moved to Failure: {Path.GetFileName(runningFileName)}");
sw.WriteLineTime($"Running file moved to Failure: {Path.GetFileName(runningFileName)}");
}
}
catch (Exception ex)
{
string affectedFile = file.Name; // Default to the file being processed
// Check if the exception is related to the running file
string runningFileName = Path.Combine(file.DirectoryName, Path.GetFileNameWithoutExtension(file.Name) + Config.Get("RunningFileName"));
if (File.Exists(runningFileName))
{
affectedFile = Path.GetFileName(runningFileName); // Update to running file name if it's related to the running file
}
// Log the exception, specifying which file failed
log.Error($"Failed to move file {affectedFile} to Failure: {ex.Message}");
sw.WriteLineTime($"Failed to move file {affectedFile} to Failure: {ex.Message}");
}
}
2025-01-14 12:09:39 Начинаем работу над: E: \Reports\Pickup\Zipped_reports01.zip
14.01.2025 12:09:39 Ошибка: файл 2872808842847_2021082_r.zip не является допустимым zip-архивом.
2025-01-14 12:09:39 ICSharpCode.SharpZipLib.Zip.ZipException: невозможно найти центральный каталог
в ICSharpCode.SharpZipLib.Zip.ZipFile.ReadEntries ()
в ICSharpCode.SharpZipLib.Zip.ZipFile..ctor(файл FileStream)
в App.MoveFile.UnpackFiles(String path, StreamWriter sw) в C:\Users\App\MoveFile.cs:line 346
2025-01-14 12:09:39 Файл-нарушитель перемещен в раздел Ошибка: Zipped_reports01.zip
14.01.2025 12:09:39 Не удалось переместить файл Zipped_reports01Running.txt в состояние Ошибка: процесс не может получить доступ к файлу, поскольку он используется другим процессом.< /p>
Подробнее здесь: https://stackoverflow.com/questions/793 ... it-is-bein
Мобильная версия