Windows get file info

GetFileAttributesA function (fileapi.h)

Retrieves file system attributes for a specified file or directory.

To get more attribute information, use the GetFileAttributesEx function.

To perform this operation as a transacted operation, use the GetFileAttributesTransacted function.

Syntax

Parameters

The name of the file or directory.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function (GetFileAttributesW), and prepend «\\?\» to the path. For more information, see File Names, Paths, and Namespaces.

Return value

If the function succeeds, the return value contains the attributes of the specified file or directory. For a list of attribute values and their descriptions, see File Attribute Constants.

If the function fails, the return value is INVALID_FILE_ATTRIBUTES. To get extended error information, call GetLastError.

Remarks

When GetFileAttributes is called on a directory that is a mounted folder, it returns the file system attributes of the directory, not those of the root directory in the volume that the mounted folder associates with the directory. To obtain the file attributes of the associated volume, call GetVolumeNameForVolumeMountPoint to obtain the name of the associated volume. Then use the resulting name in a call to GetFileAttributes. The results are the attributes of the root directory on the associated volume.

If you call GetFileAttributes for a network share, the function fails, and GetLastError returns ERROR_BAD_NETPATH. You must specify a path to a subfolder on that share.

In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.

Technology Supported
Server Message Block (SMB) 3.0 protocol Yes
SMB 3.0 Transparent Failover (TFO) Yes
SMB 3.0 with Scale-out File Shares (SO) Yes
Cluster Shared Volume File System (CsvFS) Yes
Resilient File System (ReFS) Yes

В

Symbolic link behavior—If the path points to a symbolic link, the function returns attributes for the symbolic link.

Transacted Operations

Examples

The fileapi.h header defines GetFileAttributes as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

GetFileInformationByHandleEx function (winbase.h)

Retrieves file information for the specified file.

For a more basic version of this function for desktop apps, see GetFileInformationByHandle.

To set file information using a file handle, see SetFileInformationByHandle.

Syntax

Parameters

A handle to the file that contains the information to be retrieved.

This handle should not be a pipe handle.

A FILE_INFO_BY_HANDLE_CLASS enumeration value that specifies the type of information to be retrieved.

For a table of valid values, see the Remarks section.

A pointer to the buffer that receives the requested file information. The structure that is returned corresponds to the class that is specified by FileInformationClass. For a table of valid structure types, see the Remarks section.

The size of the lpFileInformation buffer, in bytes.

Return value

If the function succeeds, the return value is nonzero and file information data is contained in the buffer pointed to by the lpFileInformation parameter.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

If FileInformationClass is FileStreamInfo and the calls succeed but no streams are returned, the error that is returned by GetLastError is ERROR_HANDLE_EOF.

Certain file information classes behave slightly differently on different operating system releases. These classes are supported by the underlying drivers, and any information they return is subject to change between operating system releases.

The following table shows the valid file information class types and their corresponding data structure types for use with this function.

FileInformationClass value lpFileInformation type
FileBasicInfo (0) FILE_BASIC_INFO
FileStandardInfo (1) FILE_STANDARD_INFO
FileNameInfo (2) FILE_NAME_INFO
FileStreamInfo (7) FILE_STREAM_INFO
FileCompressionInfo (8) FILE_COMPRESSION_INFO
FileAttributeTagInfo (9) FILE_ATTRIBUTE_TAG_INFO
FileIdBothDirectoryInfo (0xa) FILE_ID_BOTH_DIR_INFO
FileIdBothDirectoryRestartInfo (0xb) FILE_ID_BOTH_DIR_INFO
FileRemoteProtocolInfo (0xd) FILE_REMOTE_PROTOCOL_INFO
FileFullDirectoryInfo (0xe) FILE_FULL_DIR_INFO
FileFullDirectoryRestartInfo (0xf) FILE_FULL_DIR_INFO
FileStorageInfo (0x10) FILE_STORAGE_INFO
FileAlignmentInfo (0x11) FILE_ALIGNMENT_INFO
FileIdInfo (0x12) FILE_ID_INFO
FileIdExtdDirectoryInfo (0x13) FILE_ID_EXTD_DIR_INFO
FileIdExtdDirectoryRestartInfo (0x14) FILE_ID_EXTD_DIR_INFO

В

Transacted Operations

In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.

File Info Класс

Определение

Предоставляет свойства и методы экземпляра для создания, копирования, удаления, перемещения и открытия файлов, а также позволяет создавать объекты FileStream. Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. Этот класс не наследуется. This class cannot be inherited.

Читайте также:  Как остановить mysql сервер linux

Примеры

В следующем примере показаны некоторые основные члены FileInfo класса. The following example demonstrates some of the main members of the FileInfo class.

При первом извлечении свойств FileInfo вызывает Refresh метод и кэширует сведения о файле. When the properties are first retrieved, FileInfo calls the Refresh method and caches information about the file. При последующих вызовах необходимо вызвать, Refresh чтобы получить последнюю копию информации. On subsequent calls, you must call Refresh to get the latest copy of the information.

В этом примере создаются выходные данные, аналогичные приведенным ниже. This example produces output similar to the following.

Комментарии

Используйте FileInfo класс для выполнения типичных операций, таких как копирование, перемещение, переименование, создание, открытие, удаление и добавление в файлы. Use the FileInfo class for typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files.

При выполнении нескольких операций над одним и тем же файлом может оказаться более эффективным использование FileInfo методов экземпляра вместо соответствующих статических методов File класса, поскольку проверка безопасности не всегда требуется. If you are performing multiple operations on the same file, it can be more efficient to use FileInfo instance methods instead of the corresponding static methods of the File class, because a security check will not always be necessary.

Многие из FileInfo методов возвращают другие типы ввода-вывода при создании или открытии файлов. Many of the FileInfo methods return other I/O types when you create or open files. Эти другие типы можно использовать для дальнейшего управления файлом. You can use these other types to further manipulate a file. Дополнительные сведения см. в разделе определенные FileInfo элементы, такие как Open ,, OpenRead OpenText , CreateText или Create . For more information, see specific FileInfo members such as Open, OpenRead, OpenText, CreateText, or Create.

По умолчанию всем пользователям предоставляется полный доступ на чтение и запись к новым файлам. By default, full read/write access to new files is granted to all users.

В следующей таблице описаны перечисления, используемые для настройки поведения различных FileInfo методов. The following table describes the enumerations that are used to customize the behavior of various FileInfo methods.

Перечисление Enumeration Описание Description
FileAccess Указывает доступ к файлу для чтения и записи. Specifies read and write access to a file.
FileShare Указывает уровень доступа, разрешенный для уже используемого файла. Specifies the level of access permitted for a file that is already in use.
FileMode Указывает, будет ли содержимое существующего файла сохранено или перезаписано, и должны ли запросы на создание существующего файла вызывать исключение. Specifies whether the contents of an existing file are preserved or overwritten, and whether requests to create an existing file cause an exception.

В членах, принимающих путь в качестве входной строки, этот путь должен иметь правильный формат или возникнет исключение. In members that accept a path as an input string, that path must be well-formed or an exception is raised. Например, если путь является полным, но начинается с пробела, путь не усекается в методах класса. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Поэтому путь имеет неправильный формат и возникает исключение. Therefore, the path is malformed and an exception is raised. Аналогично, путь или сочетание путей не могут быть полными и дважды. Similarly, a path or a combination of paths cannot be fully qualified twice. Например, «c:\temp c:\Windows» также вызывает исключение в большинстве случаев. For example, «c:\temp c:\windows» also raises an exception in most cases. При использовании методов, принимающих строку пути, убедитесь, что пути имеют правильный формат. Ensure that your paths are well-formed when using methods that accept a path string.

В членах, принимающих путь, путь может ссылаться на файл или только на каталог. In members that accept a path, the path can refer to a file or just a directory. Указанный путь может также ссылаться на относительный путь или путь в формате UNC для имени сервера и общего ресурса. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. Например, все следующие допустимые пути: For example, all the following are acceptable paths:

«c: \ \мидир \\MyFile.txt» в C# или «c:\MyDir\MyFile.txt» в Visual Basic. «c:\\MyDir\\MyFile.txt» in C#, or «c:\MyDir\MyFile.txt» in Visual Basic.

«c: \ \мидир» в C# или «к:\мидир» в Visual Basic. «c:\\MyDir» in C#, or «c:\MyDir» in Visual Basic.

«MyDir \ \мисубдир» в C# или «мидир\мисубдир» в Visual Basic. «MyDir\\MySubdir» in C#, or «MyDir\MySubDir» in Visual Basic.

» \ \ \ \Мисервер \ \мишаре» в C# или » \ \MyServer\MyShare» в Visual Basic. «\\\\MyServer\\MyShare» in C#, or «\\MyServer\MyShare» in Visual Basic.

FileInfoКласс предоставляет следующие свойства, позволяющие получить сведения о файле. The FileInfo class provides the following properties that enable you to retrieve information about a file. Пример использования каждого свойства см. в разделе страницы свойств. For an example of how to use each property, see the property pages.

DirectoryСвойство получает объект, представляющий родительский каталог файла. The Directory property retrieves an object that represents the parent directory of a file.

DirectoryNameСвойство получает полный путь к родительскому каталогу файла. The DirectoryName property retrieves the full path of the parent directory of a file.

ExistsСвойство проверяет наличие файла перед его обработам. The Exists property checks for the presence of a file before operating on it.

IsReadOnlyСвойство извлекает или задает значение, указывающее, можно ли изменить файл. The IsReadOnly property retrieves or sets a value that specifies whether a file can be modified.

LengthВозвращает размер файла. The Length retrieves the size of a file.

NameВозвращает имя файла. The Name retrieves the name of a file.

Конструкторы

Выполняет инициализацию нового экземпляра класса FileInfo, который служит оболочкой для пути файла. Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.

Представляет полный путь к каталогу или файлу. Represents the fully qualified path of the directory or file.

(Унаследовано от FileSystemInfo) OriginalPath

Первоначально заданный пользователем относительный или абсолютный путь. The path originally specified by the user, whether relative or absolute.

(Унаследовано от FileSystemInfo)

Свойства

Получает или задает атрибуты для текущего файла или каталога. Gets or sets the attributes for the current file or directory.

(Унаследовано от FileSystemInfo) CreationTime

Получает или задает время создания текущего файла или каталога. Gets or sets the creation time of the current file or directory.

(Унаследовано от FileSystemInfo) CreationTimeUtc

Получает или задает время создания текущего файла или каталога в формате UTC. Gets or sets the creation time, in coordinated universal time (UTC), of the current file or directory.

(Унаследовано от FileSystemInfo) Directory

Получает экземпляр родительского каталога. Gets an instance of the parent directory.

Получает строку, представляющую полный путь к каталогу. Gets a string representing the directory’s full path.

Получает значение, показывающее, существует ли файл. Gets a value indicating whether a file exists.

Получает строку, содержащую расширение файла. Gets the string representing the extension part of the file.

(Унаследовано от FileSystemInfo) FullName

Получает полный путь к каталогу или файлу. Gets the full path of the directory or file.

(Унаследовано от FileSystemInfo) IsReadOnly

Возвращает или задает значение, позволяющее определить, является ли текущий файл доступным только для чтения. Gets or sets a value that determines if the current file is read only.

Получает или задает время последнего доступа к текущему файлу или каталогу. Gets or sets the time the current file or directory was last accessed.

(Унаследовано от FileSystemInfo) LastAccessTimeUtc

Получает или задает дату и время последнего доступа к заданному файлу или каталогу в формате всеобщего скоординированного времени (UTC). Gets or sets the time, in coordinated universal time (UTC), that the current file or directory was last accessed.

(Унаследовано от FileSystemInfo) LastWriteTime

Получает или задает время последней операции записи в текущий файл или каталог. Gets or sets the time when the current file or directory was last written to.

(Унаследовано от FileSystemInfo) LastWriteTimeUtc

Получает или задает время последней операции записи в текущий файл или каталог в формате всеобщего скоординированного времени (UTC). Gets or sets the time, in coordinated universal time (UTC), when the current file or directory was last written to.

(Унаследовано от FileSystemInfo) Length

Получает размер текущего файла в байтах. Gets the size, in bytes, of the current file.

Получает имя файла. Gets the name of the file.

Методы

Создает StreamWriter, который добавляет текст в файл, представленный этим экземпляром FileInfo. Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.

Копирует существующий файл в новый файл и запрещает перезапись существующего файла. Copies an existing file to a new file, disallowing the overwriting of an existing file.

Копирует существующий файл в новый файл и разрешает перезапись существующего файла. Copies an existing file to a new file, allowing the overwriting of an existing file.

Создает файл. Creates a file.

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) CreateText()

Создает StreamWriter, который записывает новый текстовый файл. Creates a StreamWriter that writes a new text file.

Расшифровывает файл, зашифрованный текущей учетной записью с помощью метода Encrypt(). Decrypts a file that was encrypted by the current account using the Encrypt() method.

Удаляет файл без возможности восстановления. Permanently deletes a file.

Шифрует файл таким образом, чтобы его можно было расшифровать только с помощью учетной записи, которая использовалась для шифрования. Encrypts a file so that only the account used to encrypt the file can decrypt it.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetAccessControl()

Возвращает объект FileSecurity, который инкапсулирует записи списка управления доступом (ACL) для файла, описываемого текущим объектом FileInfo. Gets a FileSecurity object that encapsulates the access control list (ACL) entries for the file described by the current FileInfo object.

Получает объект FileSecurity, который инкапсулирует заданный тип записей списка управления доступом для файла, описываемого текущим объектом FileInfo. Gets a FileSecurity object that encapsulates the specified type of access control list (ACL) entries for the file described by the current FileInfo object.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetObjectData(SerializationInfo, StreamingContext)

Устанавливает объект SerializationInfo с именем файла и дополнительными сведениями об исключении. Sets the SerializationInfo object with the file name and additional exception information.

(Унаследовано от FileSystemInfo) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) MoveTo(String)

Перемещает заданный файл в новое местоположение и разрешает переименование файла. Moves a specified file to a new location, providing the option to specify a new file name.

Перемещает указанный файл в новое расположение, предоставляя параметры для указания нового имени файла и перезаписи конечного файла, если он уже существует. Moves a specified file to a new location, providing the options to specify a new file name and to overwrite the destination file if it already exists.

Открывает файл в заданном режиме. Opens a file in the specified mode.

Открывает файл в заданном режиме с доступом для чтения или записи, или и для чтения, и для записи. Opens a file in the specified mode with read, write, or read/write access.

Открывает файл в заданном режиме с доступом для чтения, записи или и для чтения, и для записи и с заданным параметром совместного доступа. Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.

Создает доступный только для чтения поток FileStream. Creates a read-only FileStream.

Создает поток StreamReader с кодировкой UTF-8, который считывает данные из существующего текстового файла. Creates a StreamReader with UTF8 encoding that reads from an existing text file.

Создает доступный только для чтения поток FileStream. Creates a write-only FileStream.

Обновляет состояние объекта. Refreshes the state of the object.

(Унаследовано от FileSystemInfo) Replace(String, String)

Заменяет содержимое заданного файла на содержимое файла, которое описано в текущем объекте FileInfo, удаляет исходный файл и создает резервную копию замененного файла. Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.

Заменяет содержимое заданного файла на содержимое файла, которое описано в текущем объекте FileInfo, удаляет исходный файл и создает резервную копию замененного файла. Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file. Также позволяет определить, нужно ли игнорировать ошибки слияния. Also specifies whether to ignore merge errors.

Применяет записи списка управления доступом (ACL), описанные объектом FileSecurity, к файлу, который описывается текущим объектом FileInfo. Applies access control list (ACL) entries described by a FileSecurity object to the file described by the current FileInfo object.

Возвращает путь в виде строки. Returns the path as a string. Используйте свойство Name для полного пути. Use the Name property for the full path.

Методы расширения

Создает файловый поток с указанными свойствами и параметрами безопасности. Creates a new file stream, ensuring it is created with the specified properties and security settings.

Возвращает сведения о безопасности для файла. Returns the security information of a file.

Возвращает сведения о безопасности для файла. Returns the security information of a file.

Изменяет атрибуты безопасности для существующего файла. Changes the security attributes of an existing file.

Читайте также:  Кнопка home windows 10
Оцените статью