本文介绍如何在打包的 WinUI 应用中使用 .NET API 访问文件和文件夹。 你将了解如何读取和写入文件、管理目录和驱动器,以及处理用于字符串编码和解码的内存流。
WinUI 应用可以将 .NET API 与 WinRT 和 Win32 API 一起使用,以提供全面的文件系统访问。 本文中的示例侧重于 System.IO 命名空间,该命名空间提供文件和目录作的核心功能。
先决条件
- 安装了 WinUI 应用程序开发 工作负载的 Visual Studio 2022
- 打包的 WinUI 项目
- 基本熟悉 C# 和 .NET 开发
您将了解到的内容
本文将指导如何进行以下操作:
- 使用 FileStream、BinaryWriter 和 BinaryReader 读取和写入文件
- 使用 DirectoryInfo 和 Directory 类创建、删除和管理目录
- 使用 DriveInfo 检索驱动器信息
- 使用 MemoryStream 和 StreamReader 对字符串进行编码和解码
使用 .NET API 读取和写入文件
在以下示例中,ReadWriteFiles 创建一个新文件,将一组整数写入文件,然后从文件中读取整数。 该示例使用 FileStream 类创建新文件,并打开文件进行读取或写入。 该示例使用 BinaryWriter 类将整数写入文件,BinaryReader 类从文件中读取整数。
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());
}
}
}
在 .NET 中管理驱动器和文件夹
以下示例演示如何使用 DirectoryInfo 和 Directory 类来创建、删除和管理文件夹。 该示例使用 DirectoryInfo 类创建新目录、创建子目录和删除目录。
DirectoryInfo 类提供了用于创建、移动和枚举目录和子目录的方法。
Directory 类提供了 静态 方法,用于通过目录和子目录创建、移动和枚举。
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());
}
}
此示例使用静态 GetDrives 方法检索系统上所有驱动器的相关信息。 DriveInfo 类提供有关驱动器的信息,例如驱动器类型、标签、文件系统和可用可用空间。
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 ");
}
}
}
使用 MemoryStream 对字符串进行编码和解码
此示例演示如何使用 MemoryStream 类对字符串数据进行编码和解码。 它首先创建一个 MemoryStream 以异步方式将字符串写入内存流,然后从内存流中读取字符串。
编码 类用于将字符串转换为字节数组,然后将字节数组写入内存流。 然后,StreamReader 用于从内存流异步读取字节数组,然后通过调用 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);
}
注释
有关在 .NET 流和 WinRT 流之间进行转换的信息,请参阅 如何:在 .NET 和 Windows 运行时流之间进行转换。