File Handling

Files can be managed using the WinAPI object, along with the System.IO.FileInfo object. Let’s start with some simple, but useful, examples.

Example 1: Does a file exist?

public boolean getFileExists(filepath _fileName)
{
  System.IO.FileInfo   fileInfo;
  new InteropPermission(InteropKind::ClrInterop).assert();
  fileInfo = new System.IO.FileInfo(_fileName);
  return fileInfo.get_Exists();
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
if (fileInteractions.getFileExists(YourPath))
 info(‘The file exists!’);

_____________________________________________________________________________________

Example 2: What is a file’s extension?
public FilenameType getFileExtensionFromPath(filePath _filePath)
{
  fileNameType         fileExtension;
  System.IO.FileInfo   fileInfo;
  new InteropPermission(InteropKind::ClrInterop).assert();
  fileInfo = new System.IO.FileInfo(_filePath);
  fileExtension = fileInfo.get_Extension();
  return strLwr(fileExtension);
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
FilenameType    fileExtension;
fileExtension = fileInteractions.getFileExtensionFromPath(YourPath);
info(‘The file extension is ‘ + fileExtension);
_____________________________________________________________________________________
 
Example 3: Get a file’s name from a full path
public Filename getFileNameFromPath(filePath _filePath)
{
  fileName             fileName;
  System.IO.FileInfo   fileInfo;
  new InteropPermission(InteropKind::ClrInterop).assert();
  fileInfo = new System.IO.FileInfo(_filePath);
  fileName = fileInfo.get_Name();
  return fileName;
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
Filename        file_name;
file_name = fileInteractions.getFileNameFromPath(YourPath);
info(‘The file name is ‘ + file_name);
    _____________________________________________________________________________________
Example 4: Get a file’s last modified date
public utcDateTime getFileDateTime(filename _fileName)
{
  utcDateTime          fileDate;
  System.IO.FileInfo   fileInfo;
  new InteropPermission(InteropKind::ClrInterop).assert();
  fileInfo = new System.IO.FileInfo(_fileName);
  fileDate =  fileInfo.get_LastWriteTime();
  return fileDate;
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
utcDateTime     fileLastModified;
fileLastModified = fileInteractions.getFileDateTime(YourPath);
    _____________________________________________________________________________________
Example 5: Copy a file to a different folder
public void copyFileToFolder(filePath _sourceFilePath, filePath _destinationFilePath)
{
  //this method is used for copying a file from one folder
  //to another. It does not provide a dialog interface.
  //The file name does not change, just the folder name
  InteropPermission           permission;
  System.IO.FileInfo          file, tempfile;
  FilePath                    destinationFullPath;
  Filename                    fileName;
  permission  = new InteropPermission(InteropKind::ClrInterop);    //grant standard permissions
  permission.assert();
  file = new System.IO.FileInfo(_sourceFilePath);                  //create file object
  if (file.get_Exists())                                           //it exists.
  {
    fileName = file.get_Name();
    destinationFullPath = strFind(_destinationFilePath, @\’, strLen(_destinationFilePath) – 1, 1) == 0 ?
                         _destinationFilePath + @’
\‘ + fileName :
                         _destinationFilePath + fileName;

    tempfile =  file.CopyTo(destinationFullPath, true);  //copy and overwrite the existing file
  }
  else
  {
   error("Could not copy the file.");
  }
  CodeAccessPermission::revertAssert();
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
fileInteractions.copyFileToFolder(YourSource, YourDestination);
    _____________________________________________________________________________________
Example 6: Display the standard “Browse for Folder” window
public filePath browseForFolder(str _caption, filePath _selectedPath, boolean _showNewFolderButton)
{
  filePath  destinationFolder;
  destinationFolder = WinAPI::browseForFolderDialog(_caption, _selectedPath, _showNewFolderButton);
  return destinationFolder;
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
filePath        destinationFolder;
destinationFolder = fileInteractions.browseForFolder("Select a destination folder:", "", true);
    _____________________________________________________________________________________
Example 7: Display the standard “Save As” dialog and make a copy of a file
public void saveFileAs(HWND winHandle, filePath sourceFilePath, container fileFilter,
                       filePath initialPath, str dialogTitle)
{
  //this method is used for calling the standard windows
  //"Save As" dialog, and making a copy of the file
  //where the user selects.
  #define.OFN_READONLY            (0×00000001)
  #define.OFN_OVERWRITEPROMPT     (0×00000002)
  #define.OFN_HIDEREADONLY        (0×00000004)
  #define.OFN_NOCHANGEDIR         (0×00000008)
  #define.OFN_SHOWHELP            (0×00000010)
  #define.OFN_ENABLEHOOK          (0×00000020)
  #define.OFN_ENABLETEMPLATE      (0×00000040)
  #define.OFN_ENABLETEMPLATEHANDLE(0×00000080)
  #define.OFN_NOVALIDATE          (0×00000100)
  #define.OFN_ALLOWMULTISELECT    (0×00000200)
  #define.OFN_EXTENSIONDIFFERENT  (0×00000400)
  #define.OFN_PATHMUSTEXIST       (0×00000800)
  #define.OFN_FILEMUSTEXIST       (0×00001000)
  #define.OFN_CREATEPROMPT        (0×00002000)
  #define.OFN_SHAREAWARE          (0×00004000)
  #define.OFN_NOREADONLYRETURN    (0×00008000)
  #define.OFN_NOTESTFILECREATE    (0×00010000)
  #define.OFN_NONETWORKBUTTON     (0×00020000)
  #define.OFN_NOLONGNAMES         (0×00040000)
  #define.OFN_EXPLORER            (0×00080000)
  #define.OFN_NODEREFERENCELINKS  (0×00100000)
  #define.OFN_LONGNAMES           (0×00200000)
  #define.OFN_FORCESSHOWHIDDEN    (0×00001000)
  FilePath                    filepath;
  FilenameType                filetype;
  Filename                    filename;
  InteropPermission           permission;
  System.IO.FileInfo          file, tempfile;
  int                         flags = #OFN_PATHMUSTEXIST +
                                      #OFN_OVERWRITEPROMPT +
                                      #OFN_CREATEPROMPT +
                                      #OFN_FORCESSHOWHIDDEN +
                                      #OFN_NOCHANGEDIR;
  FilePath                    returnedFileName;
  ///////////////////////////////////////////////////////////////////
  [filepath, filename, filetype] = fileNameSplit(sourceFilePath);
  returnedFileName = WinAPI::getSaveFileName(winHandle,
                                             fileFilter,
                                             initialPath,
                                             dialogTitle,
                                             strRem(filetype, ‘.’),
                                             filename,
                                             flags);
  if (returnedFileName)   //the user didn’t cancel
  {
   permission  = new InteropPermission(InteropKind::ClrInterop);    //standard permissions
   permission.assert();
   file = new System.IO.FileInfo(sourceFilePath);                   //create file object
   if (file.get_Exists())                                           //if it exists
   {
    tempfile =  file.CopyTo(returnedFileName, true);               //copy and overwrite existing version
   }
   else
   {
    error("Could not save the file.");
   }
   CodeAccessPermission::revertAssert();
  }
}
Sample usage: ================================================================================================
YourClassName   fileInteractions = new YourClassName();
fileInteractions.saveFileAs(element.hWnd(), PathToYourFile, "*.txt", "", "Save File As");
    _____________________________________________________________________________________
Example 8: Execute a Shell command like “Open”, “Print” or “Properties”
Note that this example uses two new Base Enums which I created. You will need to create them yourself for this code to work. The definition for these are as follows:

\\Data Dictionary\Base Enums\zFileCopyOptions\eDoNotCopyToTemporaryFolder = 0
\\Data Dictionary\Base Enums\zFileCopyOptions\eCopyToTemporaryFolder = 1

\\Data Dictionary\Base Enums\zFileShellOperations\eOpen = 0
\\Data Dictionary\Base Enums\zFileShellOperations\ePrint = 1
\\Data Dictionary\Base Enums\zFileShellOperations\eProperties = 2

public void executeShellCommand(FilePath _filePath, zFileShellOperations _operation,
                                zFileCopyOptions _copyToTemporaryLocation,
                                filePath _temporaryLocation = )
{
  //this method is used for interacting with files via the
  //standard shellexecute function in the Windows API. Obviously,
  //the caller needs to have a registered piece of software to
  //actually execute the commands on the document.
  //the supported commands are…
  // open
  // print
  // properties
  //again, the caller needs to have these commands registered
  //on their computer, otherwise nothing will happen.
  InteropPermission           permission;
  System.IO.FileInfo          file, tempfile;
  fileName                    tempfileName, fileName;
  FilenameType                fileExtension;
  FilePath                    fullFilePath;
  str                         fileOperation;
  boolean                     filePathValid;
  //grant ourselves permission to operate with the file system…
  permission  = new InteropPermission(InteropKind::ClrInterop);
  permission.assert();
  //define the file object
  file = new System.IO.FileInfo(_filePath);
  //now interact with the file…
  if (file.get_Exists())
  {
   //the file exists. if we’re supposed to place a copy of
   //it into a temporary folder before we work on it, copy it out of its location
   //and put in it into the temporary location…
   switch (_copyToTemporaryLocation)
   {
    case zFileCopyOptions::eDoNotCopyToTemporaryFolder:
     //we are not copying the file to a temporary folder
     //we’re going to work with the file in its current location
     fullFilePath = file.get_FullName();
     filePathValid = true;
     break;
    case zFileCopyOptions::eCopyToTemporaryFolder:
     //we are copying the file to a temporary location
     //we need to apply a datecode to the file name
     //so we don’t have conflicts with any existing files
     filePathValid = false;
     if (WinAPI::folderExists(_temporaryLocation) == true)
     {
      //it’s a valid path. prepare the file for copying
      fileName = file.get_Name();
      fileExtension = file.get_Extension();
      tempfileName = strRem(fileName, fileExtension) + ‘ ‘ +
                     strRem(strFmt("%1" + ‘-’ + "%2",
                             date2str(systemDateGet(), 321,2,1,2,1,4),
                             time2str(timeNow(), 3,1)), ‘ ‘) +
                     fileExtension;
      tempfile =  file.CopyTo(_temporaryLocation + tempfileName, true);
      fullFilePath = tempfile.get_FullName();
      filePathValid = true;
     }
     break;
    default:
     filePathValid = false;
     break;
   }
   //////////////////////////////////////////////////////////////////
   if (filePathValid == true)
   {
    switch (_operation)
    {
     case zFileShellOperations::eOpen:
      fileOperation = ‘Open’;
      break;
     case zFileShellOperations::ePrint:
      fileOperation = ‘Print’;
      break;
     case zFileShellOperations::eProperties:
      fileOperation = ‘Properties’;
      break;
     default:
      fileOperation = ‘Open’;
      break;
    }
    WinAPI::shellExecute(fullFilePath, , , fileOperation, 0, false);
   }
   else
   {
    error(#InvalidPath);
   }
   //////////////////////////////////////////////////////////////////
  }
  CodeAccessPermission::revertAssert();     //remove our permissions
}
Sample usage: ================================================================================================
YourClassName         fileInteractions = new YourClassName();
System.IO.FileInfo    file;
file = new System.IO.FileInfo(YourFileLocation);
fileInteractions.executeShellCommand(file.get_FullName(),
                                     zFileShellOperations::eOpen,
                                     zFileCopyOptions::eDoNotCopyToTemporaryFolder);
    _____________________________________________________________________________________
Example 9:
Attach a list of files to a new Microsoft Outlook email
Note that I’ve created a new Base Enum for this example. You’ll need to create this yourself in the AOT. The definition is as follows:


\\Data Dictionary\Base Enums\zEmailSendOptions\eDisplay = 0
\\Data Dictionary\Base Enums\zEmailSendOptions\eSend = 1

public void attachFilesToEmail(List _fileList, str _emailSubject, str _htmlBody,
                               str _emailTo, str _emailCC, zEmailSendOptions _displayOrSend)
{
  //this method is used for attaching a list
  //of files to a new email in Microsoft Outlook
  //the email is displayed on the user’s screen, or can be
  //sent automatically if there is a value in the "TO" field
  #SysOutlookCOMDEF
  #define.outlook("Outlook.Application")
  #define.mapi("MAPI")
  COM                         sysOutlook;
  COM                         sysOutlookNameSpace;
  COM                         sysOutlookMailItem;
  COM                         sysOutlookAttachment;
  COM                         sysOutlookRecipient;
  InteropPermission           permission;
  System.IO.FileInfo          file;
  int                         i;
  ListEnumerator              iEnum;
  ///////////////////////////////////////////////////////
  sysOutlook = new COM(#outlook);
  sysOutlookNameSpace = sysOutlook.getNameSpace(#mapi);
  sysOutlookNameSpace.logon();
  sysOutlookMailItem = sysOutlook.CreateItem(‘Outlook.OlItemType.olMailItem’);
  sysOutlookMailItem.subject(_emailSubject);
  sysOutlookMailItem.htmlbody(_htmlBody);
  sysOutlookMailItem.to(_emailTo);
  sysOutlookMailItem.cc(_emailCC);
  sysOutlookAttachment = sysOutlookMailItem.Attachments();
  permission  = new InteropPermission(InteropKind::ClrInterop);
  permission.assert();
  iEnum = _fileList.getEnumerator();
  iEnum.reset();
  for (i = 1; i <= _fileList.elements(); i++)
   {
    iEnum.moveNext();
    file = new System.IO.FileInfo(iEnum.current());
    if (file.get_Exists())
    {
     sysOutlookAttachment.add(iEnum.current(), 1, 1, ‘New’);
    }
    else
    {
     error("The file does not exist.");
    }
   }
   CodeAccessPermission::revertAssert();
   switch (_displayOrSend)
   {
    case zEmailSendOptions::eDisplay:
     sysOutlookMailItem.display();
     break;
    case zEmailSendOptions::eSend:
     switch (strLen(strLRTrim(_emailTo)))
     {
      case 0:
       sysOutlookMailItem.display();
       break;
      default:
       sysOutlookMailItem.send();
       break;
     }
   }
   sysOutlookNameSpace.logoff();
}
Sample usage: ================================================================================================
YourClassName         fileInteractions = new YourClassName();
List                  iList = new List(Types::String);
iList.addEnd(YourFilePath);
fileInteractions.attachFilesToEmail(iList, "", "", "", "", zEmailSendOptions::eDisplay);

Comments