A folder is not deleted if it contains unclosed files - page 2

 
Rashid Umarov:

For some reason, the operating system does not allow to delete the file - either it is opened by another program, or it is not authorised enough.

Exactly like this. When I try to delete a folder that already contains subfolders and files, I delete the files first. Only the subfolders remain. I try to clean them using FolderClean() and then call FolderDelete(). However, the result is that those subfolders that were empty are well deleted, but if there were more subfolders inside the subfolders they are not deleted. After that, I try to remove the folders from the file navigator in MetaEditor manually, but the terminal does not remove them and pops up this window:

I click on "Continue", agree to the changes, but the folder is still not erased. After completely closing and reopening the terminal, the folders that should have been erased either disappear on their own or not, but you can erase them immediately and manually without the above window.

Such oddities...

 
Vladimir Karputov:

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

The functions work identically on both terminals. The file sandbox of the terminal where the script is running is used. These are native files of the terminal in use. Believe me, this is definitely not the problem...
 
Rashid Umarov:


PS And in general - not to give the program logs is to force others to guess by coffee grounds

Take a look at this gif:



I gave the code for this script above, on the previous page.

 

I should add that the folders that I'm trying to erase first software and then manually aren't open anywhere. Moreover, they cannot be opened anywhere except the file navigator itself in MetaEditor, because they are empty and the files from them were previously erased. The erased files have not been opened anywhere either.

The window asking for administrator approval to manually erase folders in the file navigator in MetaEditor only appears when trying to erase those folders that the program tried to erase using FolderClean() and FolderDelete() earlier. This window never appears when trying to delete other folders.

 
Реter Konow:

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

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

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

Can I ask why there is no file closure? Or am I just not seeing it?

Here's a snippet of your code from opening the file to asking for deletion...

   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() нельзя использовать в индикаторах!
 
//--- выведем диалоговое окно и просим пользователя 
 
Alexey Viktorov:

May I ask why there is no closing of the file? Or am I just not seeing it?

Here is a snippet of your code from the opening of the file to the question about deleting...

As far as I know, if no changes have been made to the file using file functions (e.g. FileWrite()), there is no need to close it. The FileOpen() function just creates a new file and this operation does not require closing the file (the documentation for this function, too, does not say that the file should be closed after creation). In addition, this script is taken from the documentation and I haven't changed anything there. I just added lines with FolderClean() function.
 
Реter Konow:
As far as I know, if no changes have been made to the file using FileWrite(), there is no need to close it. The FileOpen() function simply creates a new file and this operation does not require closing the file. In addition, this script is taken from the documentation and I did not change anything there. I just added lines with the FolderClean() function.

But if you look through the code using the debugger, you will see that immediately after FileOpen() is executed, there is a file with null size on disk. And there are rather many errors and inaccuracies in the documentation.

 
Alexey Viktorov:

But if you go through the code with the debugger, there is a zero-sized file on the disk right after FileOpen() is executed. And there are rather many errors and inaccuracies in the documentation.

So it should be zero size for this example.

Now I will try to explicitly close the file in the script and try again.

 
Реter Konow:

So it should be zero size for this example.

I'm going to try an explicit file close in the script and try again.

I rarely look at sample codes, and I've deleted the folder without any problems. So 99% sure that's the problem.
 

The result is the same.

Here is the new code:

//+------------------------------------------------------------------+ 
//|                                            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) 
     {
//*************************************************************************     
   //---- Явно закрываем файл.   
      FileClose(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("Удаление отменено"); 
//--- 
  }
Reason: