You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NSIS自定义页面用PathFileExists验证合法文件夹路径

问题描述

用户现有一段NSIS脚本(如下),用于检查输入路径是否来自固定驱动器;现在需要在自定义页面中替换验证逻辑:不再使用GetDriveType,改用合适的Windows API实现类似iffileexists "$path\*.*"的验证效果,但无需目标目录实际存在,仅需验证路径格式是否为合法文件夹格式。

原脚本:

!include nsdialogs.nsh
!define fixed 3
var path
var text
page custom page
function page
  nsdialogs::create 1018
    ${nsd_createtext} 0 0 100% 12u ""
    pop $text
  ${nsd_onchange} $text change
  nsdialogs::show
functionend
function change
  ${nsd_gettext} $text $path
  strcpy $0 $path 1
  system::call 'kernel32::GetDriveType(t"$0:")i.r0'
  ${if} $0 <> ${fixed}
    messagebox mb_ok ""
  ${endif}
functionend
section
sectionend
解决方案

要实现仅验证文件夹路径格式合法性(无需目录实际存在),应使用shlwapi.dll中的PathIsDirectoryName API,该函数专门用于判断字符串是否符合合法目录路径的格式要求,完全匹配需求。修改后的脚本如下:

!include nsdialogs.nsh
var path
var text
page custom page

function page
  nsdialogs::create 1018
    ${nsd_createtext} 0 0 100% 12u ""
    pop $text
  ${nsd_onchange} $text change
  nsdialogs::show
functionend

function change
  ${nsd_gettext} $text $path
  ; 移除输入内容的首尾空格,避免空格导致的误判
  StrTrim $path $path
  ; 调用PathIsDirectoryName验证路径格式
  System::Call 'shlwapi::PathIsDirectoryName(t"$path")i.r0'
  ${if} $0 == 0
    MessageBox MB_OK "请输入合法的文件夹路径格式!"
  ${endif}
functionend

section
sectionend

关键说明

  • PathIsDirectoryName返回非零值表示路径格式合法,返回0则格式不合法,无需依赖目录实际存在。
  • 增加StrTrim处理是为了过滤用户输入的首尾无效空格,可根据实际需求选择保留或移除。
  • 若坚持要使用PathFileExists,需注意该API仅能验证已存在的路径,无法满足“无需目录实际存在”的要求,因此不适用本次场景。

内容的提问来源于stack exchange,提问作者Jairo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 11:47:21