Using Environment variables to load a file from My Pictures
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]
var
  ImageFileName, FullFileName: string;
  BufSize: Integer;
  NewPath: String;
begin
  // Retrieve the contents of the edit field into a local variable for ease of use.
  ImageFileName := Edit1.Text;
  // If it exists in the working path, use that as our retrieval point.
  // Otherwise, look in the Application directory, then the My Pictures folder,
  // then look in the Windows directory
  if (FileExists(ImageFileName))
  then FullFileName := ImageFileName // Working directory needs no path.
  else if (FileExists(ExtractFilePath(Application.ExeName) + ImageFileName))
  then FullFileName := ExtractFilePath(Application.ExeName) + ImageFileName // Grab the path from the application executible info
  else begin
    // Use environmental variables to locate two other possible places
    // Allow 254 character paths to be returned.
    SetLength(NewPath, 254);
    // Call ExpandEnvironmentStrings with string containing environmental variables
    BufSize := ExpandEnvironmentStrings(‘%userprofile%\My Documents\My Pictures\’, PChar(NewPath), 254);
    // The returned BuffSize must be used to truncate off any extra garbage &  injections.
    SetLength(NewPath, BufSize – 1);
    //  Look for it and if it is found, assign the full name otherwise keep looking.
    if (FileExists(NewPath + ImageFileName))
    then FullFileName := NewPath + ImageFileName
    else begin
      // Repeat the above process for the Windows Directory.
      SetLength(NewPath, 254);
      BufSize := ExpandEnvironmentStrings(‘%windir%\’, PChar(NewPath), 254);
      SetLength(NewPath, BufSize – 1);
      if (FileExists(NewPath + ImageFileName))
      then FullFileName := NewPath + ImageFileName
      else FullFileName :=’NOT FOUND’;
    end;
  end;
[/delphi]
