How do I open a file with the default text editor?

Hidden picture Hidden · Jun 5, 2013 · Viewed 10.3k times · Source

I want to open a *.conf file. I want to open this file with the standard Windows editor (e.g., notepad.exe).

I currently have this ShellExecute code:

var
  sPath, conf: String;
begin
  try
  sPath := GetCurrentDir + '\conf\';
  conf := 'nginx.conf';
ShellExecute(Application.Handle, 'open', PChar(conf), '', Pchar(sPath+conf), SW_SHOW);
  except
    ShowMessage('Invalid config path.');
  end;
end; 

But nothing happens. So what should I change?

Answer

David Heffernan picture David Heffernan · Jun 5, 2013

How do I open a file with the default text editor?

You need to use ShellExecuteEx and use the lpClass member of SHELLEXECUTEINFO to specify that you want to treat the file as a text file. Like this:

procedure OpenAsTextFile(const FileName: string);
var
  sei: TShellExecuteInfo;
begin
  ZeroMemory(@sei, SizeOf(sei));
  sei.cbSize := SizeOf(sei);
  sei.fMask := SEE_MASK_CLASSNAME;
  sei.lpFile := PChar(FileName);
  sei.lpClass := '.txt';
  sei.nShow := SW_SHOWNORMAL;
  ShellExecuteEx(@sei);
end;

Pass the full path to the file as FileName.