1

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?

Squashman
  • 13,649
  • 5
  • 27
  • 36
HackR_360
  • 192
  • 2
  • 9

4 Answers4

3

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".
    )
)
aschipfl
  • 33,626
  • 12
  • 54
  • 99
1
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

Community
  • 1
  • 1
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
)
lit
  • 14,456
  • 10
  • 65
  • 119
0

With Dir ... /AD shows only the directories. If it is not found, then an error is fired:

If Exist "%PathFile%" (
    Dir /B /AD "%PathFile%" 1>nul 2>nul && (
         Echo It is a directory.
    ) || (
        Echo It is a file.
    )
) else (
     Echo Folder or file does not exist.
)

Note: If %PathFile% contains the keyword * of ?, Dir could waste a lot of time. It is better to filter before this. I left it for your implementation.

elpezganzo
  • 349
  • 4
  • 7