A folder is not deleted if it contains unclosed files

 
 

Why does the FolderClean() function in this script fail?

//+------------------------------------------------------------------+ 
//|                                            Demo_FolderDelete.mq5 | 
//|                        Copyright 2011, MetaQuotes Software Corp. | 
//|                                              https://www.mql5.com | 
//+------------------------------------------------------------------+ 
#property copyright "Copyright 2011, MetaQuotes Software Corp." 
#property link      "https://www.mql5.com" 
#property version   "1.00" 
//--- описание 
#property description "Скрипт показывает пример использования FolderDelete()." 
#property description "Сначала создаются две папки, одна пустая, другая содержит файл." 
#property description "При попытке удаления непустой папки получим ошибку и предупреждение."
 
//--- покажем окно входных параметров при запуске скрипта 
#property script_show_inputs 
//--- входные параметры 
input string   firstFolder="empty";    // пустая папка 
input string   secondFolder="nonempty";// папка, в которой будет один файл 
string filename="delete_me.txt";       // имя файла, который мы создадим в папке secondFolder 
//+------------------------------------------------------------------+ 
//| Script program start function                                    | 
//+------------------------------------------------------------------+ 
void OnStart() 
  { 
//--- хендл файла запишем сюда 
   int handle; 
//--- выясним в какой папке мы работаем 
   string working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL4\\Files"; 
//--- отладочное сообщение    
   PrintFormat("working_folder=%s",working_folder); 
//--- попытка создать пустую папку относительно пути MQL4\Files 
   if(FolderCreate(firstFolder,0)) // 0 означает, что работаем в локальной папке терминала 
     { 
      //--- выведем полный путь до созданной папки 
      PrintFormat("Cоздали папку %s",working_folder+"\\"+firstFolder); 
      //--- сбросим код ошибки 
      ResetLastError(); 
     } 
   else 
      PrintFormat("Не удалось создать папку %s. Код ошибки %d",working_folder+"\\"+firstFolder, GetLastError());
 
//--- теперь создадим непустую папку с помощью функции FileOpen() 
   string filepath=secondFolder+"\\"+filename;  // сформируем путь для файла, который хотим открыть на запись в несуществующей папке 
   handle=FileOpen(filepath,FILE_WRITE|FILE_TXT); // флаг FILE_WRITE в данном случае обязателен, см. справку к функции FileOpen 
   if(handle!=INVALID_HANDLE) 
      PrintFormat("Открыли файл на чтение %s",working_folder+"\\"+filepath); 
   else 
      PrintFormat("Не удалось создать файл %s в папке %s. Код ошибки=",filename,secondFolder, GetLastError());
 
   Comment(StringFormat("Готовимся удалить папки %s и %s", firstFolder, secondFolder)); 
//--- Небольшая пауза в 5 секунд, чтобы мы могли прочитать сообщение на графике 
   Sleep(5000); // Sleep() нельзя использовать в индикаторах!
 
//--- выведем диалоговое окно и просим пользователя 
   int choice=MessageBox(StringFormat("Удалить папки %s и %s?", firstFolder, secondFolder), 
                         "Удаление папок", 
                         MB_YESNO|MB_ICONQUESTION); //  будут две кнопки - "Yes" и "No"
 
//--- выполним действия в зависимости от выбранного варианта 
   if(choice==IDYES) 
     { 
      //--- очистим комментарий на графике 
      Comment(""); 
      //--- выведем сообщение в журнал "Эксперты" 
      PrintFormat("Пробуем удалить папки %s и %s",firstFolder, secondFolder); 
      ResetLastError(); 
      //--- удаляем пустую папку 
      if(FolderDelete(firstFolder)) 
         //--- должны увидеть это сообщение, так как папка пустая 
         PrintFormat("Папка %s успешно удалена",firstFolder); 
      else 
         PrintFormat("Не удалось удалить папку %s. Код ошибки=%d", firstFolder, GetLastError());
 
      ResetLastError(); 

   //***********************************************************************************************************************   
      //--- сначала очищаем папку
      if(FolderClean(secondFolder))
         PrintFormat("Папка %s успешно очищена", secondFolder);
      else 
         //---  
         PrintFormat("Не удалось очистить папку %s. Код ошибки=%d", secondFolder, GetLastError());
   //***********************************************************************************************************************   
   
      ResetLastError(); 
        
      //--- удаляем папку, которая содержит файл               
      if(FolderDelete(secondFolder)) 
         PrintFormat("Папка %s успешно удалена", secondFolder); 
      else 
         //--- 
         PrintFormat("Не удалось удалить папку %s. Код ошибки=%d", secondFolder, GetLastError()); 
     }  

   else 
      Print("Удаление отменено"); 
//--- 
  }

An attempt to clean a folder results in error 5026 - (folder cannot be cleaned).

This script is taken from the documentation (section of FolderDelete()) and slightly modified. A folder that contains other subfolders or files must be cleared to completely remove it. A call to FolderClean() is added for this purpose.

 
Реter Konow:

Why does the FolderClean() function in this script fail?

An attempt to clear a folder results in error 5026 - (folder cannot be cleared).

This script is taken from the documentation (section of the FolderDelete() function) and slightly modified. To completely delete a folder that contains other subfolders or files, you should clear it. A call to FolderClean() is added for this purpose.


Doesn't it bother you that you are trying to enter someone else's sandbox (in MQL4)?

 
Vladimir Karputov:

Isn't it confusing that you're trying to get into someone else's sandbox (in MQL4)?

I don't quite understand you. What do you mean? I performed my experience on MT4.
 
Реter Konow:
I don't quite understand you. What do you mean by that. The experiment was done on MT4.

FileOpen:

Note

For security reasons, the MQL5 language strictly controls operations with files. The files that are handled using the MQL5 language cannot be outside the file "sandbox".

A file is opened in the client terminal folder in subfolder MQL5\Files (or in the_agent_testing_directory\MQL5\Files in case of testing). If FILE_COMMON is specified among the flags, the file will be opened in the common folder of all the client terminals \Terminal\Common\Files.

What does the old terminal have to do with it, if you are running MQL5 code?
 
Vladimir Karputov:

FileOpen:

Note

For security reasons, the MQL5 language strictly controls operations with files. The files that are handled using the MQL5 language cannot be outside the file "sandbox".

A file is opened in the client terminal folder in subfolder MQL5\Files (or in the_agent_testing_directory\MQL5\Files in case of testing). If FILE_COMMON is specified among the flags, the file is opened in the common folder of all the client terminals \Terminal\Common\Files.

This script is taken from documentation.

Here is the track in which folders are created:

string working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL4\\Files"; 

Part of the FolderDelete() function works and erases the folder that is empty. However, the FolderDelete() function will no longer work on a folder with a file because there is a file inside the folder that must first be erased. To erase it, I added a call to FolderClean() as per the instructions. However, the FolderClean() function fails for some reason and the folder with the file is not cleared. As a result, it is not erased by FolderDelete().

 
Vladimir Karputov:

FileOpen:

Note

For security reasons, the MQL5 language strictly controls operations with files. The files that are handled using the MQL5 language cannot be outside the file "sandbox".

A file is opened in the client terminal folder in subfolder MQL5\Files (or in the_agent_testing_directory\MQL5\Files in case of testing). If FILE_COMMON is specified among the flags, the file opens in the common folder of all the client terminals \Terminal\Common\Files.

What does this have to do with the old terminal if you are running the MQL5 code?
There is no difference whether it is MQL4 or MQL5. The code of this script works equally on both platforms. I tested it on MT4.
 
Реter Konow:
There is no difference whether the code is MQL4 or MQL5. The code of this script works equally on both platforms. I tested it on MT4.

Did you run the MQL5 code in the old terminal? Let me check ...

 
Vladimir Karputov:

Did you run the MQL5 code in the old terminal? Let me check ...

Believe me, there's no problem with that.
 
Реter Konow:
Believe me, there's no problem with that.

What I had to prove: old terminal DOES NOT SEE MQL5 programs. You are trying to open someone else's file sandbox in an MQL5 script.

 

Реter Konow:

However, the FolderClean() function fails for some reason and the folder with the file is not cleared. As a result, it is not erased by FolderDelete().

For some reason, the operating system won't let me delete the file - it may be opened by another program or it may not have access rights.

PS In general, not giving the program logs is forcing others to guess by coffee grounds
Reason: