Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article shows you how to access files and folders using .NET APIs in packaged WinUI apps. You'll learn to read and write files, manage directories and drives, and work with memory streams for string encoding and decoding.
WinUI apps can use .NET APIs alongside WinRT and Win32 APIs to provide comprehensive file system access. The examples in this article focus on the System.IO namespace, which provides the core functionality for file and directory operations.
Prerequisites
- Visual Studio 2022 with the WinUI application development workload installed
- A packaged WinUI project
- Basic familiarity with C# and .NET development
What you'll learn
In this article, you'll learn how to:
- Read and write files using FileStream, BinaryWriter, and BinaryReader
- Create, delete, and manage directories with DirectoryInfo and Directory classes
- Retrieve drive information using DriveInfo
- Encode and decode strings with MemoryStream and StreamReader
Read and write files with .NET APIs
In the following example, ReadWriteFiles creates a new file, writes a set of integers to the file, and then reads the integers back from the file. The example uses the FileStream class to create a new file and to open the file for reading or writing. The example uses the BinaryWriter class to write the integers to the file and the BinaryReader class to read the integers from the file.
using System.IO;
...
ReadWriteFiles("test.bin");
...
private void ReadWriteFiles(string fileName)
{
if (File.Exists(fileName))
{
Console.WriteLine($"{fileName} already exists!");
return;
}
using (FileStream fs = new(fileName, FileMode.CreateNew))
{
using BinaryWriter writer = new(fs);
for (int i = 0; i < 11; i++)
{
writer.Write(i);
}
}
using (FileStream fs = new(fileName, FileMode.Open, FileAccess.Read))
{
using BinaryReader reader = new(fs);
for (int i = 0; i < 11; i++)
{
Console.WriteLine(reader.ReadInt32());
}
}
}
Manage drives and folders in .NET
The following example shows how to use the DirectoryInfo and Directory classes to create, delete, and manage folders. The example uses the DirectoryInfo class to create a new directory, create a subdirectory, and delete the directory. The DirectoryInfo class provides methods for creating, moving, and enumerating through directories and subdirectories. The Directory class provides static methods for creating, moving, and enumerating through directories and subdirectories.
using System.IO;
...
private void FolderTest()
{
FolderManagement(@"c:\MyDir", "Projects");
}
private void FolderManagement(string path, string subfolderName)
{
DirectoryInfo di = new(path);
try
{
// Create directory if it doesn't exist
if (di.Exists)
{
Console.WriteLine("Path already exists.");
}
else
{
di.Create();
Console.WriteLine("The directory was created successfully.");
}
// Create subdirectory if it doesn't exist
string subfolderPath = Path.Combine(path, subfolderName);
if (Directory.Exists(subfolderPath))
{
Console.WriteLine("Subfolder path already exists.");
}
else
{
di.CreateSubdirectory(subfolderName);
Console.WriteLine("The subdirectory was created successfully.");
}
// Delete directory
di.Delete(true);
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception ex)
{
Console.WriteLine("The process failed: {0}", ex.ToString());
}
}
This example using the static GetDrives method to retrieve information about all drives on the system. The DriveInfo class provides information about a drive, such as the drive type, label, file system, and available free space.
using System.IO;
...
private void DriveManagement()
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo d in drives)
{
Console.WriteLine($"Drive name: {d.Name}");
Console.WriteLine($" Drive type: {d.DriveType}");
if (d.IsReady)
{
Console.WriteLine($" Volume label: {d.VolumeLabel}");
Console.WriteLine($" File system type: {d.DriveFormat}");
Console.WriteLine($" Space available to user: {d.AvailableFreeSpace, 15} bytes");
Console.WriteLine($" Total available space: {d.TotalFreeSpace, 15} bytes");
Console.WriteLine($" Total size of drive: {d.TotalSize, 15} bytes ");
}
}
}
Encode and decode strings with MemoryStream
This example shows how to use the MemoryStream class to encode and decode string data. It first creates a MemoryStream to asynchronously write a string to a memory stream and then read the string from the memory stream. The Encoding class is used to convert the string to a byte array and then write the byte array to the memory stream. A StreamReader is then used to asynchronously read the byte array from the memory stream and then convert the byte array back to a string by calling ReadToEndAsync.
using System.IO;
using System.Text;
...
private async Task EncodeDecodeStringAsync(string inputData)
{
using MemoryStream stream = new();
var inputBytes = Encoding.UTF8.GetBytes(inputData);
await stream.WriteAsync(inputBytes, 0, inputBytes.Length);
stream.Seek(0, SeekOrigin.Begin);
using StreamReader reader = new(stream);
string text = await reader.ReadToEndAsync();
Console.WriteLine(text);
}
Note
For information about converting between .NET streams and WinRT streams, see How to: Convert between .NET and Windows Runtime streams.
See also
Access files and folders with Windows App SDK and WinRT APIs
Windows developer