ms.assetid | title | description | ms.date | ms.topic | keywords | ms.localizationpriority |
---|---|---|---|---|---|---|
5931d63c-6b80-4e47-b371-ee299e308b8e | Access files and folders with Windows App SDK and .NET | Packaged Windows App SDK apps can leverage .NET APIs for reading and writing files, working with folders, and reading drive and volume information. | 06/16/2023 | article | windows 10, windows 11, windows, winui, windows app sdk, dotnet | medium |
Packaged Windows App SDK apps can leverage .NET APIs for reading and writing files, working with folders, and reading drive and volume information. Additionally, any packaged desktop app can utilize both WinRT and Win32 APIs in the Windows SDK, as well as the APIs provided in the .NET SDK. This article provides guidance on how to use the .NET System.IO APIs to read and write files, manage drives and folders, and work with memory streams to encode or decode string data.
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.
usingSystem.IO; ...ReadWriteFiles("test.bin"); ... private void ReadWriteFiles(stringfileName){if(File.Exists(fileName)){Console.WriteLine($"{fileName} already exists!");return;}using(FileStreamfs=new(fileName,FileMode.CreateNew)){usingBinaryWriterwriter=new(fs);for(inti=0;i<11;i++){writer.Write(i);}}using(FileStreamfs=new(fileName,FileMode.Open,FileAccess.Read)){usingBinaryReaderreader=new(fs);for(inti=0;i<11;i++){Console.WriteLine(reader.ReadInt32());}}}
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.
usingSystem.IO; ... private void FolderTest(){FolderManagement(@"c:\MyDir","Projects");}privatevoidFolderManagement(stringpath,stringsubfolderName){DirectoryInfodi=new(path);try{// Create directory if it doesn't existif(di.Exists){Console.WriteLine("Path already exists.");}else{di.Create();Console.WriteLine("The directory was created successfully.");}// Create subdirectory if it doesn't existstringsubfolderPath=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 directorydi.Delete(true);Console.WriteLine("The directory was deleted successfully.");}catch(Exceptionex){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.
usingSystem.IO; ... private void DriveManagement(){DriveInfo[]drives=DriveInfo.GetDrives();foreach(DriveInfodindrives){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 ");}}}
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.
usingSystem.IO;usingSystem.Text; ... private async Task EncodeDecodeStringAsync(stringinputData){usingMemoryStreamstream=new();varinputBytes=Encoding.UTF8.GetBytes(inputData);awaitstream.WriteAsync(inputBytes,0,inputBytes.Length);stream.Seek(0,SeekOrigin.Begin);usingStreamReaderreader=new(stream);stringtext=awaitreader.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.
Access files and folders with Windows App SDK and WinRT APIs