How to traverse a directory in Axapta

This example list all files in a directory including sub-directories. Handy when you need to do something with a number of files stored in a structure of folders. Here we lists all the text files it can find, you only need to alter the FO_ProcessFile() method for your needs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
static void FO_ListTreeExample(Args _args)
{
    void FO_ProcessFile(FilePath _path, FileName _name)
    {
        ;
        info( strfmt(" %1 / %2 ", _path, _name) );
    }
 
    void FO_ProcessFolder(FilePath _path, FileName _mask)
    #WinApi
    {
        FileName   fileName;
        container  fileInfo;
        int        fileHandle, attrs;
        ;
 
        // traverse all sub-directories
        fileInfo = WinApi::findFirstFile(_path + "\\*.*");
        fileHandle = conpeek(fileInfo,1);
        fileName = conpeek(fileInfo,2);
        while(fileName != '')
        {
            if(fileName != '..' && fileName != '.')
            {
                attrs = WinApi::getFileAttributes(
                                _path + "\\"+fileName);
                if(attrs & #FILE_ATTRIBUTE_DIRECTORY)
                    FO_ProcessFolder(_path+'\\'+fileName, 
                                                _mask);
            }
            fileName = WinApi::findNextFile(fileHandle);
        }
 
        // traverse all files on this level
        fileInfo = WinApi::findFirstFile(_path+"\\"+_mask);
        fileHandle = conpeek(fileInfo,1);
        fileName = conpeek(fileInfo,2);
        while(fileName != '')
        {
            if(fileName != '..' && fileName != '.')
            {
                attrs = WinApi::getFileAttributes(
                                _path + "\\"+fileName);
                if( !(attrs & #FILE_ATTRIBUTE_DIRECTORY) )
                    FO_ProcessFile(_path, fileName);
            }
            fileName = WinApi::findNextFile(fileHandle);
        }
    };
 
    FO_ProcessFolder("c:\\Temp", "*.txt");
}

Last 5 posts in Development

7 thoughts on “How to traverse a directory in Axapta

  1. This won’t work, actually.
    At least, it is not supposed to work.

    Because you provide the mask from the very beginning, only text files in the current directory will be found and other directories and files won’t even be looked at.

  2. Update added. Fully tested this time … 🙂 Observe, written and tested on AX4, but it’s rather basic so it should work on prev. versions to.

    /Henrik

  3. you have no idea how you much you helped,i am working on 3 other major things,and i dont have time to look into it…
    really thanks henrik,you made somone’s day 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *