- Directory. Exists(String) Метод
- Определение
- Параметры
- Возвращаемое значение
- Примеры
- Комментарии
- How to check if directory exists in %PATH%?
- 22 Answers 22
- How can I check if a directory exists?
- 6 Answers 6
- How to test if a file is a directory in a batch script?
- 22 Answers 22
- The NUL technique seems to only work on 8.3 compliant file names.
- (In other words, `D:\Documents and Settings` is «bad» and `D:\DOCUME
Directory. Exists(String) Метод
Определение
Определяет, указывает ли заданный путь на существующий каталог на диске. Determines whether the given path refers to an existing directory on disk.
Параметры
Проверяемый путь. The path to test.
Возвращаемое значение
true , если path ссылается на существующий каталог; значение false , если каталог не существует или если при попытке определить, существует ли указанный каталог. true if path refers to an existing directory; false if the directory does not exist or an error occurs when trying to determine if the specified directory exists.
Примеры
В следующем примере в командной строке принимается массив имен файлов или каталогов, определяется тип имени и обрабатывается соответствующим образом. The following example takes an array of file or directory names on the command line, determines what kind of name it is, and processes it appropriately.
Комментарии
path Параметр может указывать сведения относительного или абсолютного пути. The path parameter is permitted to specify relative or absolute path information. Сведения об относительном пути интерпретируется как относительно текущего рабочего каталога. Relative path information is interpreted as relative to the current working directory.
Конечные пробелы удаляются из конца path параметра перед проверкой существования каталога. Trailing spaces are removed from the end of the path parameter before checking whether the directory exists.
path Параметр не учитывает регистр. The path parameter is not case-sensitive.
Если у вас нет разрешения на доступ только для чтения к каталогу, Exists метод возвратит значение false . If you do not have at a minimum read-only permission to the directory, the Exists method will return false .
Метод возвращает значение, если возникла Exists false Ошибка при попытке определить, существует ли указанный файл. The Exists method returns false if any error occurs while trying to determine if the specified file exists. Это может произойти в ситуациях, когда вызываются такие исключения, как передача имени файла с недопустимыми символами или слишком много символов, неудачный или отсутствующий диск или если вызывающий объект не имеет разрешения на чтение файла. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
How to check if directory exists in %PATH%?
How does one check if a directory is already present in the PATH environment variable? Here’s a start. All I’ve managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you’d think it would enumerate all the directories in %PATH%, but it only gets the first one.
Is there a better way of doing this? Something like find or findstr operating on the %PATH% variable? I’d just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.
22 Answers 22
First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.
For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.
From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:
The trailing \ is optional in a path
Most paths work equally well both with and without the trailing \ . The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \ . This is probably the most common practical issue when searching a PATH for a match.
- There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C)
Some paths have alternate short names
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.
Windows accepts both / and \ as folder separators within a path.
This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts)
Windows treats consecutive folder separators as one logical separator.
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match.
- Exceptions: Not only is C: , different than C:\ , but C:\ (a valid path), is different than C:\\ (an invalid path).
Windows trims trailing dots and spaces from file and directory names.
«C:\test. » is equivalent to «C:\test» .
The current .\ and parent ..\ folder specifiers may appear within a path
Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child
A path can optionally be enclosed within double quotes.
A path is often enclosed in quotes to protect against special characters like , ; ^ & = . Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ; , but the quotes may be present never-the-less.
A path may be fully qualified or relative.
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:
- D: is relative to the current working directory of volume D:
- \myPath is relative to the current working volume (could be C:, D: etc.)
- myPath is relative to the current working volume and directory
It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\ . But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.
So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The
s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 — 6, and partially addresses issue 7. The
s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the
s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format.
The problem with
s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with : but not : , where is either \ or / . UNC paths are always fully qualified and must start with \\ . When comparing fully qualified paths we use the
s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.
There are some additional issues that complicate this problem:
9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;»C:\& THE OTHER THING» is perfectly valid, but it cannot be expanded safely using simple expansion because both «%PATH%» and %PATH% will fail.
10) The path delimiter is also valid within a path name
A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.
So we can combine the
s modifier and path classification techniques along with my variation of jeb’s PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.
The function can be used like so (assuming the batch file is named inPath.bat):
Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn’t there. This is normally done simply by using something like path %path%;%newPath% . But Issue 9 demonstrates how this is not reliable.
Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled.
How can I check if a directory exists?
How can I check if a directory exists on Linux in C?
6 Answers 6
You can use opendir() and check if ENOENT == errno on failure:
Use the following code to check if a folder exists. It works on both Windows & Linux platforms.
You might use stat() and pass it the address of a struct stat , then check its member st_mode for having S_IFDIR set.
The best way is probably trying to open it, using just opendir() for instance.
Note that it’s always best to try to use a filesystem resource, and handling any errors occuring because it doesn’t exist, rather than just checking and then later trying. There is an obvious race condition in the latter approach.
According to man(2)stat you can use the S_ISDIR macro on the st_mode field:
Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.
You may also use access in combination with opendir to determine if the directory exists, and, if the name exists, but is not a directory. For example:
How to test if a file is a directory in a batch script?
Is there any way to find out if a file is a directory?
I have the file name in a variable. In Perl I can do this:
22 Answers 22
You can do it like so:
However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:
si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.
(Note — the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)
1\» echo It’s a directory – MarioVilas Jun 6 ’13 at 14:08
si* ECHO IS FOLDER – Jakob Sternberg Jan 3 ’14 at 4:16
Works with directory names that contains spaces:
Note that the quotes are necessary if the directory contains spaces:
Can also be expressed as:
This is safe to try at home, kids!
1\» echo It’s a directory – MarioVilas Jun 6 ’13 at 14:10
Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the files attributes and cut first char
f1 . It expands paths like . and .. to real path. – WesternGun Feb 8 at 22:59
Further to my previous offering, I find this also works:
No quotes around %1 are needed because the caller will supply them. This saves one entire keystroke over my answer of a year ago 😉
Here’s a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.
Sample output with the above saved as «isdir.bat»:
This works perfectly
1 to remove quotes from %1, and add a backslash at end. Then put thw whole into qutes again.
A variation of @batchman61’s approach (checking the Directory attribute).
This time I use an external ‘find’ command.
(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)
- Directories.
- Directory symbolic links or junctions.
- Broken directory symbolic links or junctions. (Doesn’t try to resolve links.)
- Directories which you have no read permission on (e.g. «C:\System Volume Information»)
The NUL technique seems to only work on 8.3 compliant file names.
(In other words, `D:\Documents and Settings` is «bad» and `D:\DOCUME
I think there is some difficulty using the «NUL» tecnique when there are SPACES in the directory name, such as «Documents and Settings.»
I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe
Here are some examples of what DID NOT work and what DOES WORK for me:
(These are all demonstrations done «live» at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)
This DID NOT work:
D:\Documents and Settings>if exist «D:\Documents and Settings\NUL» echo yes
This DID NOT work:
D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes
This DOES work (for me):
D:\Documents and Settings>cd ..
D:\>REM get the short 8.3 name for the file
Volume in drive D has no label. Volume Serial Number is 34BE-F9C9
Directory of D:\
09/25/2008 05:09 PM 2008
09/25/2008 05:14 PM 200809
1.25 2008.09.25
09/23/2008 03:44 PM BOOST_
3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME
1.EXE ChromeSetup.exe
02/14/2008 12:32 PM cygwin
[[Look right here . ]]
09/25/2008 08:34 AM DOCUME
1 Documents and Settings
09/11/2008 01:57 PM 0 EMPTY_
1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM NATION
1 National Instruments Downloads
10/12/2007 11:25 AM NVIDIA
05/13/2008 09:42 AM Office10
09/19/2008 11:08 AM PROGRA
1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM TEMP
02/14/2008 12:26 PM tmp
01/21/2008 07:05 PM VXIPNP
09/23/2008 12:15 PM WINDOWS
02/21/2008 03:49 PM wx28
02/29/2008 01:47 PM WXWIDG
2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free
D:\>REM now use the \NUL test with the 8.3 name
D:\>if exist d:\docume
This works, but it’s sort of silly, because the dot already implies i am in a directory:
D:\Documents and Settings>if exist .\NUL echo yes