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");
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.