如何检查给定的路径是否指向文件或目录? [英] How to check if given path points to a file or a directory?

查看:130
本文介绍了如何检查给定的路径是否指向文件或目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如如何查找C:\Windows\something.tmp是文件还是目录?

How to find out for example if C:\Windows\something.tmp is a file or a directory?

有时,应用程序将其临时数据写入带有扩展名的文件夹,并且删除目录与删除文件不同.因此,我必须为此调用另一个子例程.

Sometimes applications write their temporary data to a folder with an extension, and deleting a directory differs from deleting a file. So I must call a different subroutine for that.

推荐答案

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

The solution below works both for ordinary and network cases. There is much confusion and has even been heated arguments about distinguishing between files and folders. One reason is that the method familiar from the MS-DOS days (testing for the nul) is no more the valid solution to distinguish between a file and a folder in the Windows command-line. (This is getting complicated.)

@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

这篇关于如何检查给定的路径是否指向文件或目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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