如何使用默认的文本编辑器打开文件? [英] How do I open a file with the default text editor?

查看:352
本文介绍了如何使用默认的文本编辑器打开文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我目前有此ShellExecute代码:

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?

推荐答案

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

The main problem is that you use nginx.conf as the file name. You need the fully-qualified file name (with drive and directory). If the file resides in the same directory as your EXE, you should do

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

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

There is no need to set the directory, and you should normally use SW_SHOWNORMAL.

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

Also, this only works if the system running the application has the file associations set up properly for .conf files. If the system running the application opens .conf files with MS Paint, then the line above will start MS Paint. If there are no associations at all, the line won't work.

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

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

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

Now we start notepad.exe and pass the file name as the first argument.

第三,您不应使用尝试..除外,您现在要这样做。 ShellExecute 可能由于无效的配置路径之外的其他原因而失败,并且在任何情况下都不会引发异常。相反,请考虑

Third, you shouldn't use try..except the way you do now. The ShellExecute may fail for other reasons than 'invalid config path', and in any case, it won't raise an exception. Instead, consider

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

现在,回到主要问题。我的第一个代码段仅在运行您的应用程序的系统碰巧具有 .conf 文件的文件关联帖子时起作用,而第二个代码段将始终打开记事本。更好的替代方法是使用用于打开 .txt 文件的应用程序。大卫的答案举了一个例子。

Now, back to the main issue. My first code snippet only works if the system running your application happens to have an appropriate file association post for .conf files, while the second will always open Notepad. A better alternative might be to use the application used to open .txt files. David's answer gives an example of this.

这篇关于如何使用默认的文本编辑器打开文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆