Use the File.exists method in C# to check if a file exits in C# or not.
Firstly, check whether the file is present in the current directory.
After that check whether the file exist in a directory or not.
Let us see the complete example to check if a file exists in C#.
Содержание
- Определение
- Параметры
- Возвраты
- Примеры
- Комментарии
- Безопасность
- Problem:
- Solution:
- Anzeige
- Search
- Categories
- Privacy Overview
Определение
Определяет, существует ли заданный файл. Determines whether the specified file exists.
Параметры
Проверяемый файл. The file to check.
Возвраты
Значение true , если вызывающий оператор имеет требуемые разрешения и path содержит имя существующего файла; в противном случае — false . true if the caller has the required permissions and path contains the name of an existing file; otherwise, false . Этот метод также возвращает false , если path — null , недействительный путь или строка нулевой длины. This method also returns false if path is null , an invalid path, or a zero-length string. Если у вызывающего оператора нет достаточных полномочий на чтение заданного файла, исключения не создаются, а данный метод возвращает false вне зависимости от существования path . If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of path .
Примеры
В следующем примере определяется, существует ли файл. The following example determines if a file exists.
Комментарии
Метод Exists не должен использоваться для проверки пути, этот метод просто проверяет, существует ли файл, указанный в path . The Exists method should not be used for path validation, this method merely checks if the file specified in path exists. Передача недопустимого пути в Exists возвращает false . Passing an invalid path to Exists returns false . Чтобы проверить, содержит ли путь недопустимые символы, можно вызвать метод GetInvalidPathChars, чтобы получить символы, недопустимые для файловой системы. To check whether the path contains any invalid characters, you can call the GetInvalidPathChars method to retrieve the characters that are invalid for the file system. Можно также создать регулярное выражение для проверки того, является ли путь допустимым для вашей среды. You can also create a regular expression to test the whether the path is valid for your environment. Примеры допустимых путей см. в разделе File. For examples of acceptable paths, see File.
Чтобы проверить, существует ли каталог, см. раздел Directory.Exists. To check if a directory exists, see Directory.Exists.
Имейте в виду, что другой процесс может сделать что-то с файлом в промежутке между моментом вызова метода Exists и выполнения другой операции с файлом, например Delete. Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.
Для параметра 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. Сведения о получении текущего рабочего каталога см. в разделе GetCurrentDirectory. To obtain the current working directory, see GetCurrentDirectory.
Если path описывает каталог, этот метод возвращает false . If path describes a directory, this method returns false . Конечные пробелы удаляются из параметра path перед тем, как определить, существует ли файл. Trailing spaces are removed from the path parameter before determining if the file exists.
Метод 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.
Безопасность
FileIOPermission
для чтения из указанного файла. for reading from the specified file. Связанное перечисление: Read Associated enumeration: Read
Problem:
In C++ you want to check if a given file exists, but you can’t use stat() because your code needs to work cross-plaform.
Solution:
This solution is 100% portable (stat() isn’t, even if it it’s widely support), but note that it opens the file, so it might fail if it exists, but the user who is running the program isn’t allowed to access it
If you have the filename as std::string rather than as cstring, you can use this snippet:
If you know for a fact that you have access to stat() I recommend using stat instead. See this followup blog post for an example on how to do this.
Anzeige
Search
Categories
- Algorithms (5)
- Allgemein (41)
- Android (1)
- Angular (7)
- APIs (2)
- Arduino (3)
- Audio (1)
- Bioinformatics (11)
- Boost (4)
- CAD (1)
- Calculators (10)
- cloud-init (1)
- Container (54)
- Docker (38)
- Kubernetes (10)
- Cryptography (8)
- Data science (4)
- E-Mail (1)
- Electronics (68)
- Compliance (4)
- Embedded (29)
- MicroPython (2)
- Raspberry Pi (5)
- EMI (1)
- FPGA (1)
- KiCAD (4)
- Frameworks (12)
- WordPress (12)
- Fun (1)
- Generators (3)
- Geoinformatics (2)
- Hardware (3)
- Linux (120)
- Machine learning (2)
- Mathematics (9)
- Networking (9)
- nginx (14)
- OpenCASCADE (29)
- PDF (5)
- Performance (4)
- Physics (1)
- Programming languages (403)
- C/C++ (118)
- GCC errors (23)
- Go (9)
- Haskell (8)
- Haxe (2)
- HTML (2)
- Java (5)
- Javascript (63)
- NodeJS (28)
- LaTeX (22)
- Octave (9)
- PHP (12)
- Python (138)
- R (1)
- Ruby (1)
- Shell (15)
- Typescript (3)
- C/C++ (118)
- Project management (30)
- Build systems (19)
- CMake (12)
- Version management (7)
- git (6)
- Subversion (2)
- Build systems (19)
- Statistics (6)
- Technologies (90)
- Cloud (23)
- Databases (42)
- ElasticSearch (22)
- MongoDB (2)
- SQLite (6)
- GPU (1)
- LLVM (2)
- OpenCV (3)
- Puppeteer (17)
- Virtualization (3)
- Video (3)
- Windows (5)
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
Источник: