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

 
Реter Konow:

I mean, did you make an EA out of a script and try to run it?

Why redo it? Too lazy to check, but if you try the FILE_SHARE_READ andFILE_SHARE_WRITE flags
 
A100 And try FILE_COMMON everywhere

STARIJ Why redo it? I'm too lazy to check, but if you try the FILE_SHARE_READ andFILE_SHARE_WRITE flags

The thing is, it's unclear what these flags have to do with FolderClean(). Not at all, in my opinion.

I want to prove that it's not about the file at all. I'll re-do the script so that it creates a "DeleteMe.txt" folder instead of the "notempty" folder, and then it erases this folder, just like it tried to do with the file before. Let's see if it makes a difference).

Automated Trading and Strategy Testing
Automated Trading and Strategy Testing
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
Реter Konow:

The thing is, it's unclear what these flags have to do with FolderClean(). Not at all, in my opinion.

a folder can be deleted if there are no files in it, or if it can be removed. These flags allow access to the file

 
Реter Konow:

I mean, did you make an EA out of a script and try to run it?

Where did I say I made an EA?

 

I have to say that indeed, explicitly closing the file works. I guess I was wrong. The first time it didn't work, probably because I didn't save a new version of the redesigned script and the explicit closure didn't take effect.

Now I've tried creating folders instead of a file. They erased without any problems.

Then added file creation again. Result: Without explicitly closing the file, the folder is not erased by the script as before. With explicit closing of the file, it is erased completely.

Of course, this experience doesn't explain everything and some things remain hazy for now, but this result is inspiring.

I'll keep testing and will report back with results.

There may still be problems, and it's hard to say for sure right now.

 
Alexey Viktorov:

Where did I say what the councillor did?

I apologise, I misunderstood.
 

Here is the code of the script that creates both "DeleteMe.txt" and "DeleteMe Folder" file. The file explicitly closes immediately after creation.

Everything seems to work...

//+------------------------------------------------------------------+ 
//|                                            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 FolderName="delete_me Folder";       // имя файла, который мы создадим в папке secondFolder 
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());
 
//--- теперь создадим пустую папку с помощью функции FolderCreate 
   string filepath=secondFolder+"\\"+FolderName;  // сформируем путь для файла, который хотим открыть на запись в несуществующей папке 

   if(FolderCreate(filepath)) 
     { 
      FolderCreate(filepath + "1");
      PrintFormat("Открыли папку %s",working_folder+"\\"+filepath); 
     } 
   else 
      PrintFormat("Не удалось создать папку %s в папке %s. Код ошибки=",FolderName,secondFolder, GetLastError());
 /**/
 //--- теперь создадим файл с помощью функции FileOpen() 
   string filepath_2=secondFolder+"\\"+filename;  // сформируем путь для файла, который хотим открыть на запись в несуществующей папке 
   handle=FileOpen(filepath_2,FILE_WRITE|FILE_TXT); // флаг FILE_WRITE в данном случае обязателен, см. справку к функции FileOpen 
   if(handle!=INVALID_HANDLE) 
     {
//*************************************************************************     
   //---- Явно закрываем файл.   
      FileClose(handle);
//*************************************************************************           
      PrintFormat("Открыли файл на чтение %s",working_folder+"\\"+filepath_2); 
     } 
   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("Удаление отменено"); 
//--- 
  }


 
Реter Konow:

Of course, this experience doesn't explain everything and some things remain vague so far, but this result is inspiring.

I will continue testing and will report back with results.

There may still be problems and it's hard to say for sure at the moment.

Yes, of course you can, and keep the details to yourself, just say "I have changed the example from the help, nothing at all".

And we'll keep guessing - because anyone can guess with logs. And it's much more interesting that way.

 
Rashid Umarov:

Yes, of course, write. And the details keep to themselves, just say "I have changed a little example of help, nothing at all.

And we'll keep guessing - after all, with logs anyone can guess, and it's much more interesting that way.

Weird. It's nothing personal. If I'm being unprofessional, I'm sorry. I'll learn.

Thanks for your help.


P.S. I've just never asked for help on the forum. Hence the inexperience.

 

I remember your "I have all the moves written down" in the OOP vs procedural programming thread. In this thread I was just convinced that you cannot be trusted.

There is no proof and no details - no need to write to servicedesk.

Reason: