# How to test if a directory exists

The command \IfFileExists works great to test is a file exists. Is there an equivalent to test if a directory exists? \IfFileExists does not seem to work for directories.

\documentclass{article}

\begin{document}
\newcommand*{\ExistingDirName}{./ExistingDir}%       This exists
\newcommand*{\NonExistingDirName}{./NonExistingDir}% This does not exist

\newcommand*{\ExistingFileName}{\ExistingDirName/ExistingFile.tex}% This exists
\newcommand*{\NonExistingFileName}{NonExistingFile.tex}% This does not exist

\newcommand*{\CheckExistence}[1]{
\IfFileExists{#1}{
"#1" exists\par
}{
"#1" does NOT exist\par
}
}

\CheckExistence{\ExistingDirName}%    incorrect results
\CheckExistence{\NonExistingDirName}% correct result

\bigskip
\CheckExistence{\ExistingFileName}%    works
\CheckExistence{\NonExistingFileName}% works

\end{document}

-
\IfFileExists uses the TeX facility for reading a file line by line: it tries to open it for line by line reading and issues success or failure. There are two catches: (1) if a file name is given without extension, .tex is added; (2) the operating system won't allow to read a directory, which is not a readable file. –  egreg Jun 13 '11 at 20:36
+1 for a good question. Sorry, but I don't have an answer; I was just about to ask this same question myself! –  David Hammen Jun 13 '11 at 22:03
Hey is a solution, but it is ugly, suboptimal, kludgy, and insecure -- so just a comment, not a solution. Just \immediate\write18{touch \testdir/bogus_file} and then use \IfFileExists on the newly-created bogus_file. And then delete it with another write18. –  David Hammen Jun 13 '11 at 22:17
Interesting idea... But, I am trying to avoid OS specific functions. –  Peter Grill Jun 13 '11 at 22:26
@Peter Unfortunately, testing the existence of a directory is OS specific. –  egreg Jun 14 '11 at 17:46

As egreg said there is no direct test for directories. One possibility is if you are trying to read a file from within a directory then use \IfFileExists to check for its existence. If you are trying to write a file in the directory, then just try to open it for writing using \immediate\openout.