The Code Cave

April 1, 2006

Using Environment variables to load a file from My Pictures

Filed under: Delphi — Brian @ 12:39 am

It’s been a while since I used Environment Variables in Delphi and I had to look it up.

I have a loose rule that anything I have to look up, I want to share on my blog so that I can find it again easily later.

So here you have it: Enviromental Variable expansion ala Delphi.

It’s really not that complex, and it’s possible that this routine could be optimized some. But I think it works well enough as is and demonstrates the use of ExpandEnvironmentStrings quite nicely. If you need to get a list of the variables, you’ll need to do further research on GetEnvironmentStrings and FreeEnvironmentStrings to return the list to you for manipulation. A search for FreeEnvironmentStrings Delphi gives you pleanty of code examples.

Here is my example for ExpandEnvironmentStrings:

DELPHI:
  1. var
  2.   ImageFileName, FullFileName: string;
  3.   BufSize: Integer;
  4.   NewPath: String;
  5. begin
  6.   // Retrieve the contents of the edit field into a local variable for ease of use.
  7.   ImageFileName := Edit1.Text;
  8.  
  9.   // If it exists in the working path, use that as our retrieval point.
  10.   // Otherwise, look in the Application directory, then the My Pictures folder,
  11.   // then look in the Windows directory
  12.   if (FileExists(ImageFileName))
  13.   then FullFileName := ImageFileName // Working directory needs no path.
  14.   else if (FileExists(ExtractFilePath(Application.ExeName) + ImageFileName))
  15.   then FullFileName := ExtractFilePath(Application.ExeName) + ImageFileName // Grab the path from the application executible info
  16.   else begin
  17.  
  18.     // Use environmental variables to locate two other possible places
  19.     // Allow 254 character paths to be returned.
  20.     SetLength(NewPath, 254);
  21.  
  22.     // Call ExpandEnvironmentStrings with string containing environmental variables
  23.     BufSize := ExpandEnvironmentStrings(‘%userprofile%\My Documents\My Pictures\’, PChar(NewPath), 254);
  24.  
  25.     // The returned BuffSize must be used to truncate off any extra garbage &  injections.
  26.     SetLength(NewPath, BufSize - 1);
  27.  
  28.     //  Look for it and if it is found, assign the full name otherwise keep looking.
  29.     if (FileExists(NewPath + ImageFileName))
  30.     then FullFileName := NewPath + ImageFileName
  31.     else begin
  32.       // Repeat the above process for the Windows Directory.
  33.       SetLength(NewPath, 254);
  34.       BufSize := ExpandEnvironmentStrings(‘%windir%\’, PChar(NewPath), 254);
  35.       SetLength(NewPath, BufSize - 1);
  36.       if (FileExists(NewPath + ImageFileName))
  37.       then FullFileName := NewPath + ImageFileName
  38.       else FullFileName :=‘NOT FOUND’;
  39.     end;
  40.   end;

« Older Posts

Powered by WordPress