Directory.Exists(String) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет, относится ли указанный путь к существующему каталогу на диске.
public:
static bool Exists(System::String ^ path);
public static bool Exists(string path);
public static bool Exists(string? path);
static member Exists : string -> bool
Public Shared Function Exists (path As String) As Boolean
Параметры
- path
- String
Путь для тестирования.
Возвращаемое значение
Примеры
В следующем примере выполняется массив имен файлов или каталогов в командной строке, определяется тип имени и обрабатывается соответствующим образом.
// For File.Exists, Directory.Exists
using System;
using System.IO;
using System.Collections;
public class RecursiveFileProcessor
{
public static void Main(string[] args)
{
foreach(string path in args)
{
if(File.Exists(path))
{
// This path is a file
ProcessFile(path);
}
else if(Directory.Exists(path))
{
// This path is a directory
ProcessDirectory(path);
}
else
{
Console.WriteLine("{0} is not a valid file or directory.", path);
}
}
}
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
}
}
module RecursiveFileProcessor
open System.IO
// Insert logic for processing found files here.
let processFile path =
printfn $"Processed file '%s{path}'."
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
let rec processDirectory targetDirectory =
// Process the list of files found in the directory.
let fileEntries = Directory.GetFiles targetDirectory
for fileName in fileEntries do
processFile fileName
// Recurse into subdirectories of this directory.
let subdirectoryEntries = Directory.GetDirectories targetDirectory
for subdirectory in subdirectoryEntries do
processDirectory subdirectory
[<EntryPoint>]
let main args =
for path in args do
if File.Exists path then
// This path is a file
processFile path
elif Directory.Exists path then
// This path is a directory
processDirectory path
else
printfn $"{path} is not a valid file or directory."
0
' For File.Exists, Directory.Exists
Imports System.IO
Imports System.Collections
Public Class RecursiveFileProcessor
Public Overloads Shared Sub Main(ByVal args() As String)
Dim path As String
For Each path In args
If File.Exists(path) Then
' This path is a file.
ProcessFile(path)
Else
If Directory.Exists(path) Then
' This path is a directory.
ProcessDirectory(path)
Else
Console.WriteLine("{0} is not a valid file or directory.", path)
End If
End If
Next path
End Sub
' Process all files in the directory passed in, recurse on any directories
' that are found, and process the files they contain.
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub
' Insert logic for processing found files here.
Public Shared Sub ProcessFile(ByVal path As String)
Console.WriteLine("Processed file '{0}'.", path)
End Sub
End Class
Комментарии
Параметр path может указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные к текущему рабочему каталогу.
Конечные пробелы удаляются из конца path параметра перед проверкой наличия каталога.
Конфиденциальность регистра path параметра соответствует файловой системе, в которой выполняется код. Например, это не учитывает регистр в NTFS (файловая система Windows по умолчанию) и учитывает регистр в файловых системах Linux.
Если у вас нет минимального разрешения только для чтения в каталоге, Exists метод вернет false.
Метод Exists возвращается false , если при попытке определить, существует ли указанный файл. Это может произойти в ситуациях, которые вызывают исключения, такие как передача имени файла с недопустимыми символами или слишком большим количеством символов, сбой или отсутствующий диск, или если вызывающий объект не имеет разрешения на чтение файла.