Check if input is a file or folder

孤街浪徒 提交于 2021-01-29 07:54:44

问题


I have a command like this:

set /p txtfile=Write destination to the .txt file:

now i need to know if the file really exists so:

if exist %txtfile% echo file found.

it works, but if the user writes me C:\ it will display "file found" to. I want to know is there a way to know a file extension using batch, any ideas?


回答1:


You can identify it as a file using TYPE. However, it might not be the best way if it is a large file.

SET "DIR_ITEM=C:\Windows"

TYPE "%DIR_ITEM%" 1>NUL 2>&1
IF ERRORLEVEL 1 (
    ECHO "%DIR_ITEM%" is not a file
) ELSE (
    ECHO "%DIR_ITEM% is a file
)



回答2:


I assume you want to know whether the given item is an existing file but not a directory (note that directories can also have an extension). Use a trailing \ to distinguish between file and directory:

if exist "file.ext" (
    if exist "file.ext\" (
        echo The given item is a directory.
    ) else (
        echo The given item is a file.
    )
) else (
    echo The given item does not exist.
)

Or in short:

if exist "file.ext" if not exist "file.ext\" echo This is a file but not a directory.

If you really want to check the name of a given item whether or not there is an extension, you could use a for loop:

for %%I in ("file.ext") do (
    if not "%%~xI"=="" (
        echo The given item has got the extension "%%~xI".
    )
)



回答3:


pushd C:\ && (Echo Is a folder & popd) || Echo Is a file or doesn't exist 2>nul

&& is same as if not errorlevel 1 and || same as if errorlevel 1. 2>nul hide error messages. Brackets make sure line is executed as I want by grouping commands. Pushd sets errorlevel to 1 if it can't change to the specified directory else 0.

See my command cheat sheet here Command to run a .bat file



来源:https://stackoverflow.com/questions/41293209/check-if-input-is-a-file-or-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!