Windows file properties api

Windows. Storage. File Properties Namespace

Provides access to the properties of a file.

Classes

Provides access to the basic properties, like the size of the item or the date the item was last modified, of the item (like a file or folder).

Provides access to the document-related properties of an item (like a file or folder).

Provides methods for setting and retrieving geographic metadata for a file.

Provides access to the image-related properties of an item (like a file or folder).

Provides access to the music-related properties of an item (like a file or folder).

Provides access to the content-related properties of an item (like a file or folder).

Represents the thumbnail image associated with a system resource (like a file or folder).

Provides access to the video-related properties of an item (like a file or folder).

Interfaces

Saves and retrieves the properties of a storage item.

Enums

Indicates the Exchangeable Image File (EXIF) orientation flag of the photo. This flag describes how to rotate the photo to display it correctly.

Indicates a system-defined group of file properties.

Describes the purpose of the thumbnail to determine how to adjust the thumbnail image to retrieve.

Describes the behavior used to retrieve and adjust thumbnails, including the size and quality of the image and how quickly the thumbnail image is retrieved.

Indicates whether the thumbnail is an icon or an image.

Indicates how to rotate the video to display it correctly.

Записки программиста

Учимся работать с файлами через Windows API

Из предыдущих постов, посвященных WinAPI, мы научились настраивать Visual Studio и узнали, как в нем писать простые консольные приложения. Следующим маленьким шажком в изучении WinAPI будет освоение работы с файлами.

Для этого нелегкого дела нам понадобятся следующие процедуры:

В Windows для того, чтобы открыть или создать файл, нужно вызвать процедуру, имеющую целых семь аргументов. К счастью, большинство из них приходится использовать крайне редко. Аргумент szName задает имя файла, а dwAccess — желаемый доступ к файлу, обычно это GENERIC_READ, GENERIC_WRITE или оба значения, объединенные логическим или. Параметр dwShareMode определяет, что могут делать с файлом другие процессы, пока мы с ним работаем. Возможные значения — FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE и их комбинации, однако часто этот параметр просто устанавливают в ноль. Параметр dwCreationDisposition определяет, как именно мы хотим открыть файл, может быть, например, CREATE_NEW, CREATE_ALWAYS, OPEN_EXISTING, OPEN_ALWAYS. О семантике этого хозяйства нетрудно догадаться самостоятельно. С помощью dwFlags можно указать дополнительные свойства файла, например, хранить ли его в зашифрованном или сжатом виде, или сказать, что файл является скрытым, временным или системным. Обычно сюда передают FILE_ATTRIBUTE_NORMAL. Наконец, про lpSecurityAttributes и hTemplateFile сейчас знать не нужно, сюда можно смело передавать NULL.

В случае успешного создания или открытия файла, процедура CreateFile возвращает его хэндл. В случае ошибки возвращается специальное значение INVALID_HANDLE_VALUE. Узнать подробности об ошибке можно с помощью GetLastError.

Чтение из файла в буфер lpBuff размером dwBuffSize. В переменную dwCount записывается реальное количество прочитанных байт. Последний опциональный аргумент называется lpOverlapped и о нем сейчас знать не нужно.

Аргументы и семантика процедуры WriteFile полностью аналогичны ReadFile.

Файловые дескрипторы закрываются с помощью CloseHandle. На самом деле, эта процедура используется не только для работы с файлами, так что мы еще не единожды с нею встретимся.

Посмотрим теперь на все это хозяйство в действии. Следующая программа пишет в файл counter.dat количество собственных запусков. Первые пять запусков ничем не примечательны. На шестой и последующие запуски программа сообщает, что у нее истек триал и просит приобрести полную версию.

#define MAX_TRIAL_RUNS 5

const TCHAR szCounterFileName [ ] = L «counter.dat» ;
const TCHAR szMsgTmpl [ ] = L «Вы запустили программу в %d-й раз. %s.» ;
const TCHAR szCheckOk [ ] = L «Все в порядке, продолжайте работу» ;
const TCHAR szCheckFailed [ ] = L «Триал истек, купите полную версию» ;

DWORD ReadCounter ( ) <
DWORD dwCounter , dwTemp ;
HANDLE hFile = CreateFile ( szCounterFileName , GENERIC_READ , 0 , NULL ,
OPEN_EXISTING , FILE_ATTRIBUTE_NORMAL , NULL ) ;
if ( INVALID_HANDLE_VALUE == hFile ) <
return 1 ;
>
ReadFile ( hFile , & dwCounter , sizeof ( dwCounter ) , & dwTemp , NULL ) ;
if ( sizeof ( dwCounter ) != dwTemp ) <
CloseHandle ( hFile ) ;
return 1 ;
>
CloseHandle ( hFile ) ;
return dwCounter ;
>

VOID WriteCounter ( DWORD dwCounter ) <
DWORD dwTemp ;
HANDLE hFile = CreateFile ( szCounterFileName , GENERIC_WRITE , 0 , NULL ,
CREATE_ALWAYS , FILE_ATTRIBUTE_NORMAL , NULL ) ;
if ( INVALID_HANDLE_VALUE == hFile ) <
return ;
>
WriteFile ( hFile , & dwCounter , sizeof ( dwCounter ) , & dwTemp , NULL ) ;
CloseHandle ( hFile ) ;
>

int main ( ) <
TCHAR szMsg [ 256 ] ;
DWORD dwCounter = ReadCounter ( ) ;
LPCWSTR lpCheckResult = dwCounter > MAX_TRIAL_RUNS ?
szCheckFailed : szCheckOk ;
wsprintf ( szMsg , szMsgTmpl , dwCounter , lpCheckResult ) ;
MessageBox ( 0 , szMsg , L «Сообщение» , 0 ) ;

if ( dwCounter MAX_TRIAL_RUNS ) <
WriteCounter ( dwCounter + 1 ) ;
>

Как обычно, программа также успешно компилируется при помощи MinGW и запускается под Wine.

В качестве домашнего задания можете попробовать модифицировать программу так, чтобы она выводила время, когда производились все ее запуски. Для этого вам понадобятся процедуры GetLocalTime, SetFilePointer и GetFileSizeEx. Если это задание покажется вам слишком простым, попробуйте найти информацию о том, как при помощи процедур, упомянутых в этой заметке, (1) написать консольное приложение и (2) открыть диск C: на чтение, словно он является обычным файлом.

Читайте также:  Как загрузится mac os безопасный режим

Если у вас есть дополнения или возникли вопросы, смелее пишите комментарии, не стесняйтесь!

Получение свойств файла Get file properties

Важные API Important APIs

Получите свойства — верхнего уровня, базовые и расширенные — для файла, представленного объектом StorageFile. Get properties—top-level, basic, and extended—for a file represented by a StorageFile object.

Полный пример: пример доступа к файлам. For a complete sample, see the File access sample.

Необходимые компоненты Prerequisites

Общее представление об асинхронном программировании для приложений универсальной платформы Windows (UWP) . Understand async programming for Universal Windows Platform (UWP) apps

Описание процесса написания асинхронных приложений на C# или Visual Basic см. в статье Вызов асинхронных API в C# и Visual Basic. You can learn how to write asynchronous apps in C# or Visual Basic, see Call asynchronous APIs in C# or Visual Basic. Сведения о создании асинхронных приложений на C++ см. в статье Асинхронное программирование на языке C++. To learn how to write asynchronous apps in C++, see Asynchronous programming in C++.

Права доступа к расположению Access permissions to the location

Например, коду в этих примерах требуется возможность picturesLibrary. Для вашего расположения может потребоваться другая возможность либо вообще не потребоваться никаких возможностей. For example, the code in these examples require the picturesLibrary capability, but your location may require a different capability or no capability at all. Дополнительную информацию см. в разделе Разрешения на доступ к файлам. To learn more, see File access permissions.

Получение свойств файла верхнего уровня Getting a file’s top-level properties

Доступ ко многим свойствам файла верхнего уровня можно получить как к членам класса StorageFile. Many top-level file properties are accessible as members of the StorageFile class. К таким свойствам относятся атрибуты файлов, тип содержимого, дата создания, отображаемое имя, тип файла и т. д. These properties include the files attributes, content type, creation date, display name, file type, and so on.

Обязательно объявите возможность picturesLibrary. Remember to declare the picturesLibrary capability.

Этот пример перечисляет все файлы библиотеки «Изображения», предоставляя доступ к некоторым свойствам верхнего уровня каждого из файлов. This example enumerates all of the files in the Pictures library, accessing a few of each file’s top-level properties.

Получение базовых свойств файла Getting a file’s basic properties

Многие базовые свойства файла можно получить, вызвав сначала метод StorageFile.GetBasicPropertiesAsync. Many basic file properties are obtained by first calling the StorageFile.GetBasicPropertiesAsync method. Этот метод возвращает объект BasicProperties, который определяет свойства размера элемента (файл или папка) и дату его последнего изменения. This method returns a BasicProperties object, which defines properties for the size of the item (file or folder) as well as when the item was last modified.

Этот пример перечисляет все файлы библиотеки «Изображения», предоставляя доступ к некоторым базовым свойствам каждого из файлов. This example enumerates all of the files in the Pictures library, accessing a few of each file’s basic properties.

Получение расширенных свойств файла Getting a file’s extended properties

Помимо свойств верхнего уровня и базовых свойств, существует много свойств, связанных с содержимым файла. Aside from the top-level and basic file properties, there are many properties associated with the file’s contents. Доступ к этим расширенным свойствам можно получить, вызвав метод BasicProperties.RetrievePropertiesAsync. These extended properties are accessed by calling the BasicProperties.RetrievePropertiesAsync method. (Объект BasicProperties получают, вызывая свойство StorageFile.Properties.) Доступ к свойствам верхнего уровня и базовым свойствам файла можно получить, обратившись к ним как к свойствам класса (StorageFile и BasicProperties соответственно). Однако расширенные свойства получают, передавая коллекцию IEnumerable объектов String, представляющих имена свойств, которые должны быть получены методом BasicProperties.RetrievePropertiesAsync. (A BasicProperties object is obtained by calling the StorageFile.Properties property.) While top-level and basic file properties are accessible as properties of a class—StorageFile and BasicProperties, respectively—extended properties are obtained by passing an IEnumerable collection of String objects representing the names of the properties that are to be retrieved to the BasicProperties.RetrievePropertiesAsync method. Затем этот метод возвращает коллекцию IDictionary. This method then returns an IDictionary collection. После этого каждое расширенное свойство извлекается из коллекции по имени или индексу. Each extended property is then retrieved from the collection by name or by index.

Этот пример перечисляет все файлы библиотеки изображений, указывает имена нужных свойств (DataAccessed и FileOwner) в объекте List, передает объект List в BasicProperties.RetrievePropertiesAsync для извлечения свойств и затем получает свойства по имени из возвращенного объекта IDictionary. This example enumerates all of the files in the Pictures library, specifies the names of desired properties (DataAccessed and FileOwner) in a List object, passes that List object to BasicProperties.RetrievePropertiesAsync to retrieve those properties, and then retrieves those properties by name from the returned IDictionary object.

В разделе Основные свойства Windows представлен полный список расширенных свойств файла. See the Windows Core Properties for a complete list of a file’s extended properties.

Читайте также:  Javascript скрипты для windows

Set File Properties

The Set File Properties operation sets system properties on the file.

Request

The Set File Properties request may be constructed as follows. HTTPS is recommended.

Method Request URI HTTP Version
PUT https://myaccount.file.core.windows.net/myshare/mydirectorypath/myfile?comp=properties HTTP/1.1

Replace the path components shown in the request URI with your own, as follows:

Path Component Description
myaccount The name of your storage account.
myshare The name of your file share.
mydirectorypath Optional. The path to the parent directory.
myfile The name of the file.

URI Parameters

The following additional parameters may be specified on the request URI.

Parameter Description
timeout Optional. The timeout parameter is expressed in seconds. For more information, see Setting Timeouts for File Service Operations.

Request Headers

The following table describes required and optional request headers.

Request Header Description
Authorization Required. Specifies the authorization scheme, account name, and signature. For more information, see Authorize requests to Azure Storage.
Date or x-ms-date Required. Specifies the Coordinated Universal Time (UTC) for the request. For more information, see Authorize requests to Azure Storage.
x-ms-version Required for all authorized requests. Specifies the version of the operation to use for this request. For more information, see Versioning for the Azure Storage Services.
x-ms-cache-control Optional. Modifies the cache control string for the file.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-type Optional. Sets the file’s content type.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-md5 Optional. Sets the file’s MD5 hash.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-encoding Optional. Sets the file’s content encoding.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-language Optional. Sets the file’s content language.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-disposition Optional. Sets the file’s Content-Disposition header.

If this property is not specified on the request, then the property will be cleared for the file. Subsequent calls to Get File Properties will not return this property, unless it is explicitly set on the file again.

x-ms-content-length: bytes Optional. Resizes a file to the specified size. If the specified byte value is less than the current size of the file, then all ranges above the specified byte value are cleared.
x-ms-file-permission Required if x-ms-file-permission-key is not specified. Version 2019-02-02 and newer. This permission is the security descriptor for the file specified in the Security Descriptor Definition Language (SDDL). This header can be used if the permissions size is over 8 KiB, otherwise the x-ms-file-permission-key may be used. If specified, it must have an owner, group, and discretionary access control list (DACL). A value of inherit may be passed to inherit from the parent directory.

Note that only one of x-ms-file-permission or x-ms-file-permission-key can be specified.

x-ms-file-permission-key Required if x-ms-file-permission is not specified. Version 2019-02-02 and newer. The key of the permission to be set for the file. This can be created using the Create-Permission API.

Note that only one of x-ms-file-permission or x-ms-file-permission-key can be specified.

x-ms-file-attributes Required. Version 2019-02-02 and newer. The file system attributes to be set on the file. See the list of available attributes. A value of preserve may be passed to keep an existing value unchanged.
x-ms-file-creation-time Required. Version 2019-02-02 and newer. The Coordinated Universal Time (UTC) creation time property for a file. A value of now may be used to indicate the time of the request. A value of preserve may be passed to keep an existing value unchanged.
x-ms-file-last-write-time Required. Version 2019-02-02 and newer. The Coordinated Universal Time (UTC) last write property for a file. A value of now may be used to indicate the time of the request. A value of preserve may be passed to keep an existing value unchanged.
x-ms-lease-id: Required if the file has an active lease. Available for versions 2019-02-02 and later.
x-ms-client-request-id Optional. Provides a client-generated, opaque value with a 1 KiB character limit that is recorded in the analytics logs when storage analytics logging is enabled. Using this header is highly recommended for correlating client-side activities with requests received by the server. For more information, see Monitoring Azure Blob storage.

Request Body

Response

The response includes an HTTP status code and a set of response headers.

Status Code

A successful operation returns status code 200 (OK).

For information about status codes, see Status and Error Codes.

Response Headers

The response for this operation includes the following headers. The response may also include additional standard HTTP headers. All standard headers conform to the HTTP/1.1 protocol specification.

Response Header Description
ETag The ETag contains a value which represents the version of the file, in quotes.
Last-Modified Returns the date and time the directory was last modified. The date format follows RFC 1123. For more information, see Representation of Date-Time Values in Headers. Any operation that modifies the directory or its properties updates the last modified time. Operations on files do not affect the last modified time of the directory.
x-ms-request-id This header uniquely identifies the request that was made and can be used for troubleshooting the request. For more information, see Troubleshooting API Operations.
x-ms-version Indicates the version of the File service used to execute the request.
Date or x-ms-date A UTC date/time value generated by the service that indicates the time at which the response was initiated.
x-ms-request-server-encrypted: true/false Version 2017-04-17 or newer. The value of this header is set to true if the contents of the request are successfully encrypted using the specified algorithm, and false otherwise.
x-ms-file-permission-key The key of the permission of the file.
x-ms-file-attributes The file system attributes on the file. See the list of available attributes.
x-ms-file-creation-time The UTC date/time value that represents the creation time property for the file.
x-ms-file-last-write-time The UTC date/time value that represents the last write time property for the file.
x-ms-file-change-time The UTC date/time that value that represents the change time property for the file.
x-ms-client-request-id This header can be used to troubleshoot requests and corresponding responses. The value of this header is equal to the value of the x-ms-client-request-id header if it is present in the request and the value is at most 1024 visible ASCII characters. If the x-ms-client-request-id header is not present in the request, this header will not be present in the response.

Response Body

Authorization

Only the account owner may call this operation.

File system attributes

Attribute Win32 file attribute Definition
ReadOnly FILE_ATTRIBUTE_READONLY A file that is read-only. Applications can read the file, but cannot write to it or delete it.
Hidden FILE_ATTRIBUTE_HIDDEN The file is hidden. It is not included in an ordinary directory listing.
System FILE_ATTRIBUTE_SYSTEM A file that the operating system uses a part of, or uses exclusively.
None FILE_ATTRIBUTE_NORMAL A file that does not have other attributes set. This attribute is valid only when used alone.
Archive FILE_ATTRIBUTE_ARCHIVE A file that is an archive file. Applications typically use this attribute to mark files for backup or removal.
Temporary FILE_ATTRIBUTE_TEMPORARY A file that is being used for temporary storage.
Offline FILE_ATTRIBUTE_OFFLINE The data of a file is not available immediately. This file system attribute is presented primarily to provide compatibility with Windows — Azure Files does not support with offline storage options.
NotContentIndexed FILE_ATTRIBUTE_NOT_CONTENT_INDEXED The file is not to be indexed by the content indexing service.
NoScrubData FILE_ATTRIBUTE_NO_SCRUB_DATA The user data stream not to be read by the background data integrity scanner. This file system attribute is presented primarily to provide compatibility with Windows.

Remarks

The semantics for updating a file’s properties are as follows:

A file’s size is modified only if the request specifies a value for the x-ms-content-length header.

If a request sets only x-ms-content-length , and no other properties, then none of the file’s other properties are modified.

If any one or more of the following properties is set in the request, then all of these properties are set together. If a value is not provided for a given property when at least one of the properties listed below is set, then that property will be cleared for the file.

The file properties listed above are discrete from the file system properties available to SMB clients. SMB clients cannot read, write, or modify these property values.

Set File properties is not supported on a share snapshot, which is a read-only copy of a share. An attempt to perform this operation on a share snapshot will fail with 400 (InvalidQueryParameterValue)

If the file has an active lease, the client must specify a valid lease ID on the request in order to write properties to the file. If the client does not specify a lease ID, or specifies an invalid lease ID, the File service returns status code 412 (Precondition Failed). If the client specifies a lease ID but the file does not have an active lease, the File service also returns status code 412 (Precondition Failed).

Читайте также:  Как восстановить блокнот windows 10 если удалил
Оцените статью