Working with files and folders in windows

Work with files

This topic covers what you need to know to get started reading from, and writing to, files in a Universal Windows Platform (UWP) app. The main APIs and types are introduced, and links are provided to help you learn more.

This is not a tutorial. If you want a tutorial, see Create, write, and read a file which, in addition to demonstrating how to create, read, and write a file, shows how to use buffers and streams. You may also be interested in the File access sample which shows how to create, read, write, copy and delete a file, as well as how to retrieve file properties and remember a file or folder so that your app can easily access it again.

We’ll look at code to write and read text from a file and how to access the app’s local, roaming, and temporary folders.

What do you need to know

Here are the main types you need to know about to read or write text from/to a file:

Windows.Storage.StorageFile represents a file. This class has properties that provide information about the file, and methods for creating, opening, copying, deleting, and renaming files. You may be used to dealing with string paths. There are some Windows Runtime APIs that take a string path, but more often you will use a StorageFile to represent a file because some files you work with in UWP may not have a path, or may have an unwieldy path. Use StorageFile.GetFileFromPathAsync() to convert a string path to a StorageFile.

The FileIO class provides an easy way to read and write text. This class can also read/write an array of bytes, or the contents of a buffer. This class is very similar to the PathIO class. The main difference is that instead of taking a string path, as PathIO does, it takes a StorageFile.

Windows.Storage.StorageFolder represents a folder (directory). This class has methods for creating files, querying the contents of a folder, creating, renaming, and deleting folders, and properties that provide information about a folder.

Common ways to get a StorageFolder include:

  • Windows.Storage.Pickers.FolderPicker which allows the user to navigate to the folder they want to use.
  • Windows.Storage.ApplicationData.Current which provides the StorageFolder specific to one of folders local to the app like the local, roaming, and temporary folder.
  • Windows.Storage.KnownFolders which provides the StorageFolder for known libraries such as the Music or Picture libraries.

Write text to a file

For this introduction, we will focus on a simple scenario: reading and writing text. Let’s start by looking at some code that uses the FileIO class to write text to a file.

We first identify where the file should be located. Windows.Storage.ApplicationData.Current.LocalFolder provides access to the local data folder, which is created for your app when it is installed. See Access the file system for details about the folders your app can access.

Then, we use StorageFolder to create the file (or open it if it already exists).

The FileIO class provides a convenient way to write text to the file. FileIO.WriteTextAsync() replaces the entire contents of the file with the provided text. FileIO.AppendLinesAsync() appends a collection of strings to the file—writing one string per line.

Читайте также:  После установки windows 10 ноутбук выключается сам

Read text from a file

As with writing a file, reading a file starts with specifying where the file is located. We’ll use the same location as in the example above. Then we’ll use the FileIO class to read its contents.

You can also read each line of the file into individual strings in a collection with IList contents = await Windows.Storage.FileIO.ReadLinesAsync(sampleFile);

Access the file system

In the UWP platform, folder access is restricted to ensure the integrity and privacy of the user’s data.

App folders

These are some of the app folders you will commonly use:

LocalState: For data local to the current device. When the device is backed up, data in this directory is saved in a backup image in OneDrive. If the user resets or replaces the device, the data will be restored. Access this folder with Windows.Storage.ApplicationData.Current.LocalFolder. Save local data that you don’t want backed up to OneDrive in the LocalCacheFolder, which you can access with Windows.Storage.ApplicationData.Current.LocalCacheFolder .

RoamingState: For data that should be replicated on all devices where the app is installed. Windows limits the amount of data that will roam, so only save user settings and small files here. Access the roaming folder with Windows.Storage.ApplicationData.Current.RoamingFolder .

TempState: For data that may be deleted when the app isn’t running. Access this folder with Windows.Storage.ApplicationData.Current.TemporaryFolder .

Access the rest of the file system

A UWP app must declare its intent to access a specific user library by adding the corresponding capability to its manifest. The user is then prompted when the app is installed to verify that they authorize accessing the specified library. If not, the app is not installed. There are capabilities to access the pictures, videos, and music libraries. See App capability declaration for a full list. To get a StorageFolder for these libraries, use the Windows.Storage.KnownFolders class.

Documents library

Although there is a capability to access the user’s documents library, that capability is restricted which means that an app declaring it will be rejected by the Microsoft Store unless you follow a process to get special approval. It is not intended for general use. Instead, use the file or folder pickers (see Open files and folders with a picker and Save a file with a picker) which allow the user to navigate to the folder or file. When the user navigates to a folder or file, they have implicitly given permission for the app to access it and the system allows access.

General access

Alternatively, your app can declare the restricted broadFileSystem capability in its manifest, which also requires Microsoft Store approval. Then the app can access any file that the user has access to without requiring the intervention of a file or folder picker.

For a comprehensive list of the locations that apps can access, see File access permissions.

Useful APIs and docs

Here is a quick summary of APIs, and other useful documentation, to help get you started with files and folders.

Работа с файлами, папками и разделами реестра Working With Files, Folders and Registry Keys

Windows PowerShell использует существительное Item , чтобы ссылаться на элементы, найденные на диске Windows PowerShell. Windows PowerShell uses the noun Item to refer to items found on a Windows PowerShell drive. При работе с поставщиком FileSystem Windows PowerShell Item может быть файлом, папкой или диском Windows PowerShell. When dealing with the Windows PowerShell FileSystem provider, an Item might be a file, a folder, or the Windows PowerShell drive. Создание списков элементов и работа с ними является критически важной задачей в большинстве административных учреждений, поэтому необходимо подробно обсудить ее. Listing and working with these items is a critical basic task in most administrative settings, so we want to discuss these tasks in detail.

Читайте также:  Как windows oem заменить

Перечисление файлов, папок и разделов реестра (Get-ChildItem) Enumerating Files, Folders, and Registry Keys (Get-ChildItem)

Так как получение коллекции элементов из определенного расположения является обычной задачей, командлет Get-ChildItem предназначен специально для возврата всех элементов, найденных в контейнере, например в папке. Since getting a collection of items from a particular location is such a common task, the Get-ChildItem cmdlet is designed specifically to return all items found within a container such as a folder.

Если необходимо вернуть все файлы и папки, которые находятся непосредственно в папке C:\Windows, введите: If you want to return all files and folders that are contained directly within the folder C:\Windows, type:

Списки выглядят аналогично тем спискам, которые появляются при вводе команды dir в Cmd.exe или команды ls в командной оболочке UNIX. The listing looks similar to what you would see when you enter the dir command in Cmd.exe , or the ls command in a UNIX command shell.

С помощью параметров командлета Get-ChildItem можно создавать очень сложные списки. You can perform very complex listings by using parameters of the Get-ChildItem cmdlet. Далее рассмотрим несколько сценариев. We will look at a few scenarios next. Синтаксис командлета Get-ChildItem можно увидеть, введя следующее. You can see the syntax the Get-ChildItem cmdlet by typing:

Эти параметры можно скомбинировать и сопоставить для получения настраиваемых выходных данных. These parameters can be mixed and matched to get highly customized output.

Перечисление всех элементов в контейнере (-Recurse) Listing all Contained Items (-Recurse)

Чтобы увидеть оба элемента в папке Windows и все элементы во вложенных папках, используйте параметр Recurse для Get-ChildItem . To see both the items inside a Windows folder and any items that are contained within the subfolders, use the Recurse parameter of Get-ChildItem . В списке отображается все, что находится в папке Windows, а также элементы в ее вложенных папках. The listing displays everything within the Windows folder and the items in its subfolders. Пример: For example:

Фильтрация элементов по имени (-Name) Filtering Items by Name (-Name)

Чтобы отобразить только имена элементов, используйте параметр Name для Get-Childitem . To display only the names of items, use the Name parameter of Get-Childitem :

Принудительное перечисление скрытых элементов (-Force) Forcibly Listing Hidden Items (-Force)

В выходных данных команды Get-ChildItem не отображаются элементы, которые обычно невидимы в проводнике или Cmd.exe. Items that are normally invisible in File Explorer or Cmd.exe are not displayed in the output of a Get-ChildItem command. Чтобы показать скрытые элементы, используйте параметр Force для Get-ChildItem . To display hidden items, use the Force parameter of Get-ChildItem . Пример: For example:

Этот параметр называется Force, так как позволяет принудительно переопределить обычное поведение команды Get-ChildItem . This parameter is named Force because you can forcibly override the normal behavior of the Get-ChildItem command. Параметр Force широко используется для принудительного выполнения действия командлетом. Тем не менее, он не будет выполнять действия, компрометирующие систему безопасности. Force is a widely used parameter that forces an action that a cmdlet would not normally perform, although it will not perform any action that compromises the security of the system.

Сопоставление имен элементов с подстановочными знаками Matching Item Names with Wildcards

Команда Get-ChildItem принимает подстановочные знаки в пути к элементам списка. The Get-ChildItem command accepts wildcards in the path of the items to list.

Так как сопоставление с подстановочными знаками обрабатывается подсистемой Windows PowerShell, все командлеты, которые принимают подстановочные знаки, используют одну нотацию и имеют одно поведение сопоставления. Because wildcard matching is handled by the Windows PowerShell engine, all cmdlets that accepts wildcards use the same notation and have the same matching behavior. В нотацию подстановочных знаков Windows PowerShell входит: The Windows PowerShell wildcard notation includes:

Читайте также:  Radeon x1900 series драйвер windows

Звездочка ( * ) соответствует нулю или большему количеству вхождений любого символа. Asterisk ( * ) matches zero or more occurrences of any character.

Знак вопроса ( ? ) соответствует ровно одному символу. Question mark ( ? ) matches exactly one character.

Открывающая квадратная скобка ( [ ) и закрывающая квадратная скобка ( ] ) заключают в себя набор символов для сопоставления. Left bracket ( [ ) character and right bracket ( ] ) character surround a set of characters to be matched.

Далее приводится несколько примеров работы спецификации из подстановочных знаков. Here are some examples of how wildcard specification works.

Чтобы найти в каталоге Windows все файлы, имеющие суффикс .log и ровно пять символов в основном имени, введите следующую команду. To find all files in the Windows directory with the suffix .log and exactly five characters in the base name, enter the following command:

Чтобы найти в каталоге Windows все файлы с именами, начинающимися на букву x , введите следующее. To find all files that begin with the letter x in the Windows directory, type:

Чтобы найти все файлы с именами, начинающимися на x или z, введите следующее. To find all files whose names begin with «x» or «z», type:

Дополнительные сведения о подстановочных знаках см. в разделе about_Wildcards. For more information about wildcards, see about_Wildcards.

Исключение элементов (-Exclude) Excluding Items (-Exclude)

Вы можете исключить определенные элементы с помощью параметра Exclude для Get-ChildItem . You can exclude specific items by using the Exclude parameter of Get-ChildItem . Это позволит вам выполнить сложную фильтрацию в одном операторе. This lets you perform complex filtering in a single statement.

Например, вы пытаетесь найти библиотеку службы времени Windows в папке System32 и все, что вам известно об имени библиотеки, — то, что оно начинается с W и содержит 32. For example, suppose you are trying to find the Windows Time Service DLL in the System32 folder, and all you can remember about the DLL name is that it begins with «W» and has «32» in it.

Такое выражение, как w*32*.dll , найдет все библиотеки DLL, которые отвечают этим условиям, но вам может потребоваться дополнительно отфильтровать файлы и пропустить все файлы win32. An expression like w*32*.dll will find all DLLs that satisfy the conditions, but you may want to further filter out the files and omit any win32 files. Эти файлы можно пропустить с помощью параметра Exclude с шаблоном win* . You can omit these files by using the Exclude parameter with the pattern win* :

Смешение параметров Get-ChildItem Mixing Get-ChildItem Parameters

В одной команде можно использовать несколько параметров командлета Get-ChildItem . You can use several of the parameters of the Get-ChildItem cmdlet in the same command. Перед тем как комбинировать параметры, убедитесь, что понимаете принципы сопоставления подстановочных знаков. Before you mix parameters, be sure that you understand wildcard matching. Например, следующая команда не возвращает результатов: For example, the following command returns no results:

Результаты отсутствуют, даже если существуют две библиотеки, которые начинаются на букву z в папке Windows. There are no results, even though there are two DLLs that begin with the letter «z» in the Windows folder.

Результаты не возвращены, так как подстановочный знак указан как часть пути. No results were returned because we specified the wildcard as part of the path. Хотя команда и была рекурсивной, командлет Get-ChildItem ограничил элементы до тех, которые находятся в папке Windows с именами, заканчивающимися на .dll . Even though the command was recursive, the Get-ChildItem cmdlet restricted the items to those that are in the Windows folder with names ending with .dll .

Чтобы указать рекурсивный поиск для файлов, имена которых соответствуют специальному шаблону, используйте параметр Include . To specify a recursive search for files whose names match a special pattern, use the Include parameter.

Оцените статью