Using X++ to get a list of files in a directory

If you have the need to read a specific directory to get a list of files from it, the following code uses System.IO objects which will work in batch if needed.

static container findMatchingFiles(
        str _folderPath,
        str _filePattern   = '*.*')
{
    System.IO.DirectoryInfo     directory;
    System.IO.FileInfo[]        files;
    System.IO.FileInfo          file;
    InteropPermission           permission;
    str                         fileName;
    counter                     filesCount;
    counter                     loop;
    container                   matchingFiles;

    permission  = new InteropPermission(InteropKind::ClrInterop);
    permission.assert();

    directory   = new System.IO.DirectoryInfo(_folderPath);
    files       = directory.GetFiles(_filePattern);
    filesCount  = files.get_Length();

    for (loop = 0; loop < filesCount; loop++)
    {
        file            = files.GetValue(loop);
        fileName        = file.get_FullName();
        matchingFiles   = conins(matchingFiles, conlen(matchingFiles) + 1, fileName);
    }

    CodeAccessPermission::revertAssert();

    return matchingFiles;
}

The parameters of this method are the folder path to search and the file pattern (which can be left to default of all files).  This method returns a container of the file names.  You can then use code such as below to loop through the files.

for (loop = 1; loop <= conlen(files); loop++)
    {
          //Insert code here to work with each file
    }

Comments

Popular posts from this blog

Posting Purchase Order Invoices via X++

Split a production order with X++