Search code examples
fileaxaptadelete-filedynamics-ax-2012x++

How to delete file from code?


I have to delete a File from X++ code.

I used this code in my method :

TextIO textIO;

str filename, fileOpen, folder;
int handle;
Io thisMYFile;
FileIoPermission perm;

#File
#avifiles
#OCCRetryCount

[handle, filename]  =   WINAPI::findFirstFile(folder + "\\*.csv");

fileOpen = strFmt (folder + "\\" +  filename);

perm = new FileIoPermission(fileOpen, 'w');
perm.assert();

thisMYFile = new CommaTextIo(fileOpen , 'w');

 WinApi::deleteFile(fileOpen);
}

}
 catch
{}
}

The Value fileOpen is : C:\Users\myUserName\Desktop\myFolder\myFile.csv .

I can read and fill the table, but when I have to delete it, it errors with the

catch(Exception::CLRError)

(in classes\WinAPI\DeleteFile).

Is there a permission problem ?


Solution

  • You still have the file open via your thisMYFile variable.
    Set it to null before trying to delete the file:

    ...
    perm = new FileIoPermission(fileOpen, 'w');
    perm.assert();
    
    thisMYFile = new CommaTextIo(fileOpen , 'w');
    // Do stuff
    thisMYFile = null;
    
    WinApi::deleteFile(fileOpen);
    ...