【问题标题】:How to check if given path points to a file or a directory?如何检查给定的路径是否指向文件或目录?
【发布时间】:2011-11-28 10:45:34
【问题描述】:

如何判断C:\Windows\something.tmp是文件还是目录?

有时应用程序会将其临时数据写入带有扩展名的文件夹,删除目录与删除文件不同。所以我必须为此调用一个不同的子程序。

【问题讨论】:

标签: windows batch-file command-line cmd


【解决方案1】:

以下解决方案适用于普通和网络案例。关于区分文件和文件夹,存在很多混乱,甚至引起了激烈的争论。一个原因是 MS-DOS 时代熟悉的方法(测试 nul)不再是在 Windows 命令行中区分文件和文件夹的有效解决方案。 (这变得越来越复杂了。)

@echo off & setlocal enableextensions
if "%~1"=="" (
  echo Usage: %~0 [FileOrFolderName]
  goto :EOF)
::
:: Testing
call :IsFolderFn "%~1" isfolder_
call :IsFileFn "%~1" isfile_
echo "%~f1" isfile_=%isfile_% isfolder_=%isfolder_%
endlocal & goto :EOF
::
:: Is it a folder
:: First the potential case of the root requires special treatment
:IsFolderFn
setlocal
if /i "%~d1"=="%~1" if exist "%~d1\" (
  set return_=true& goto _ExitIsFolderFn)
if /i "%~d1\"=="%~1" if exist "%~d1" (
  set return_=true& goto _ExitIsFolderFn)
set return_=
dir /a:d "%~1" 2>&1|find "<DIR>">nul
if %errorlevel% EQU 0 set return_=true
:_ExitIsFolderFn
endlocal & set "%2=%return_%" & goto :EOF
::
:: Is it just a file
:IsFileFn
setlocal
set return_=
if not exist "%~1" goto _ExitIsFileFn
call :IsFolderFn "%~1" isfold_
if defined isfold_ goto _ExitIsFileFn
dir /a:-d "%~1" 2>&1 > nul
if %errorlevel% EQU 0 set return_=true
:_ExitIsFileFn
endlocal & set "%2=%return_%" & goto :EOF

原文来自http://www.netikka.net/tsneti/info/tscmd075.htm

【讨论】:

    【解决方案2】:

    How to test if a file is a directory in a batch script?

    简而言之:

    FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory
    

    但所有学分都归Dave Webb

    【讨论】:

      【解决方案3】:

      你可以用dir /a-d告诉你

      如果我检查错误级别,它会告诉我

      有文件

      C:\Users\preet>echo. > something.tmp
      
      C:\Users\preet>dir /a-d something.tmp > nul & echo %errorlevel%
      1
      
      C:\Users\preet>del something.tmp
      

      有目录

      C:\Users\preet>md something.tmp
      
      C:\Users\preet>dir /a-d something.tmp > nul & echo %errorlevel%
      File Not Found
      0
      

      【讨论】:

        猜你喜欢
        • 2012-11-30
        • 2015-07-30
        • 1970-01-01
        • 2011-08-22
        • 2018-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多