如何使用默认文本编辑器打开文件?

问题描述 投票:2回答:3

我想打开一个* .conf文件。我想用标准Windows编辑器(例如notepad.exe)打开此文件。

我目前有这个ShellExecute代码:

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; 

但没有任何反应。那么我应该改变什么呢?

delphi configuration-files shellexecute
3个回答
3
投票

主要问题是您使用nginx.conf作为文件名。您需要完全限定的文件名(包含驱动器和目录)。如果文件与EXE位于同一目录中,则应该这样做

ShellExecute(Handle, nil,
  PChar(ExtractFilePath(Application.ExeName) + 'nginx.conf'),
  nil, nil, SW_SHOWNORMAL)

无需设置目录,通常应使用SW_SHOWNORMAL

此外,这仅在运行应用程序的系统为.conf文件正确设置了文件关联时才有效。如果运行应用程序的系统使用MS Paint打开.conf文件,则上面的行将启动MS Paint。如果根本没有关联,则该行将不起作用。

您可以手动指定使用notepad.exe

ShellExecute(Handle, nil, PChar('notepad.exe'),
  PChar(ExtractFilePath(Application.ExeName) + 'nginx.conf'),
  nil, SW_SHOWNORMAL)

现在我们启动notepad.exe并将文件名作为第一个参数传递。

第三,你不应该像现在这样使用try..except。由于“无效配置路径”之外的其他原因,ShellExecute可能会失败,并且在任何情况下,它都不会引发异常。相反,考虑一下

if FileExists(...) then
  ShellExecute(...)
else
  MessageBox(Handle, 'Invalid path to configuration file', 'Error', MB_ICONERROR)

现在,回到主要问题。我的第一个代码片段仅在运行您的应用程序的系统恰好具有.conf文件的适当文件关联帖子时才有效,而第二个代码片段将始终打开记事本。更好的选择可能是使用用于打开.txt文件的应用程序。大卫的回答给出了一个例子。


7
投票

如何使用默认文本编辑器打开文件?

您需要使用ShellExecuteEx并使用lpClassSHELLEXECUTEINFO成员指定您要将文件视为文本文件。像这样:

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;

将完整路径作为FileName传递给文件。


0
投票

使用

ShellExecute(0, 'Open', PChar(AFile), nil, '', 1{SW_SHOWNORMAL});

在Delphi DX10中定义了这个函数

Winapi.ShellAPI

© www.soinside.com 2019 - 2024. All rights reserved.