Skip to content

Commit fd5fe1f

Browse files
committed
Update .NET file and folder examples
1 parent 9482a1d commit fd5fe1f

File tree

2 files changed

+132
-0
lines changed

2 files changed

+132
-0
lines changed

hub/apps/develop/files/dotnet-files.md

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,140 @@ Packaged Windows App SDK apps can leverage .NET APIs for reading and writing fil
1313

1414
## Read and write files with .NET APIs
1515

16+
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](/dotnet/api/system.io.filestream) class to create a new file and to open the file for reading or writing. The example uses the [BinaryWriter](/dotnet/api/system.io.binarywriter) class to write the integers to the file and the [BinaryReader](/dotnet/api/system.io.binaryreader) class to read the integers from the file.
17+
18+
```csharp
19+
using System.IO;
20+
...
21+
ReadWriteFiles("test.bin");
22+
...
23+
private void ReadWriteFiles(string fileName)
24+
{
25+
if (File.Exists(fileName))
26+
{
27+
Console.WriteLine($"{fileName} already exists!");
28+
return;
29+
}
30+
31+
using (FileStream fs = new(fileName, FileMode.CreateNew))
32+
{
33+
using BinaryWriter writer = new(fs);
34+
for (int i = 0; i < 11; i++)
35+
{
36+
writer.Write(i);
37+
}
38+
}
39+
40+
using (FileStream fs = new(fileName, FileMode.Open, FileAccess.Read))
41+
{
42+
using BinaryReader reader = new(fs);
43+
for (int i = 0; i < 11; i++)
44+
{
45+
Console.WriteLine(reader.ReadInt32());
46+
}
47+
}
48+
}
49+
```
50+
1651
## Manage drives and folders in .NET
1752

53+
The following example shows how to use the [DirectoryInfo](/dotnet/api/system.io.directoryinfo) and [Directory](/dotnet/api/system.io.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.
54+
55+
```csharp
56+
using System.IO;
57+
...
58+
private void FolderTest()
59+
{
60+
FolderManagement(@"c:\MyDir", "Projects");
61+
}
62+
private void FolderManagement(string path, string subfolderName)
63+
{
64+
DirectoryInfo di = new(path);
65+
try
66+
{
67+
// Create directory if it doesn't exist
68+
if (di.Exists)
69+
{
70+
Console.WriteLine("Path already exists.");
71+
}
72+
else
73+
{
74+
di.Create();
75+
Console.WriteLine("The directory was created successfully.");
76+
}
77+
78+
// Create subdirectory if it doesn't exist
79+
string subfolderPath = Path.Combine(path, subfolderName);
80+
if (Directory.Exists(subfolderPath))
81+
{
82+
Console.WriteLine("Subfolder path already exists.");
83+
}
84+
else
85+
{
86+
di.CreateSubdirectory(subfolderName);
87+
Console.WriteLine("The subdirectory was created successfully.");
88+
}
89+
90+
// Delete directory
91+
di.Delete(true);
92+
Console.WriteLine("The directory was deleted successfully.");
93+
}
94+
catch (Exception ex)
95+
{
96+
Console.WriteLine("The process failed: {0}", ex.ToString());
97+
}
98+
}
99+
```
100+
101+
This example using the static [GetDrives](/dotnet/api/system.io.driveinfo.getdrives) method to retrieve information about all drives on the system. The [DriveInfo](/dotnet/api/system.io.driveinfo) class provides information about a drive, such as the drive type, label, file system, and available free space.
102+
103+
```csharp
104+
using System.IO;
105+
...
106+
private void DriveManagement()
107+
{
108+
DriveInfo[] drives = DriveInfo.GetDrives();
109+
110+
foreach (DriveInfo d in drives)
111+
{
112+
Console.WriteLine($"Drive name: {d.Name}");
113+
Console.WriteLine($" Drive type: {d.DriveType}");
114+
if (d.IsReady)
115+
{
116+
Console.WriteLine($" Volume label: {d.VolumeLabel}");
117+
Console.WriteLine($" File system type: {d.DriveFormat}");
118+
Console.WriteLine($" Space available to user: {d.AvailableFreeSpace, 15} bytes");
119+
Console.WriteLine($" Total available space: {d.TotalFreeSpace, 15} bytes");
120+
Console.WriteLine($" Total size of drive: {d.TotalSize, 15} bytes ");
121+
}
122+
}
123+
}
124+
```
125+
18126
## Encode and decode strings with MemoryStream
19127

128+
This example shows how to use the [MemoryStream](/dotnet/api/system.io.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](/dotnet/api/system.text.encoding) class is used to convert the string to a byte array and then write the byte array to the memory stream. A [StreamReader](/dotnet/api/system.io.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](/dotnet/api/system.io.streamreader.readtoendasync).
129+
130+
```csharp
131+
using System.IO;
132+
using System.Text;
133+
...
134+
private async Task EncodeDecodeStringAsync(string inputData)
135+
{
136+
using MemoryStream stream = new();
137+
var inputBytes = Encoding.UTF8.GetBytes(inputData);
138+
await stream.WriteAsync(inputBytes, 0, inputBytes.Length);
139+
stream.Seek(0, SeekOrigin.Begin);
140+
141+
using StreamReader reader = new(stream);
142+
string text = await reader.ReadToEndAsync();
143+
Console.WriteLine(text);
144+
}
145+
```
146+
147+
> [!NOTE]
148+
> For informatio about converting between .NET streams and WinRT streams, see [How to: Convert between .NET and Windows Runtime streams](/dotnet/standard/io/how-to-convert-between-dotnet-streams-and-winrt-streams).
149+
20150
## See also
21151

22152
[Access files and folders with Windows App SDK and WinRT APIs](winrt-files.md)

hub/apps/develop/files/winrt-files.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Packaged Windows App SDK apps can leverage [WinRT APIs](/uwp/api/) for reading a
1616
The following example shows how to use the [StorageFolder](/uwp/api/windows.storage.storagefolder) and [StorageFile](/uwp/api/windows.storage.storagefile) APIs to query the **Documents** library for files and folders. The example uses the `GetFilesInFolderAsync` method to recursively iterate through the folder structure and append the file names to a `StringBuilder` object.
1717

1818
```csharp
19+
using System.Text;
1920
using Windows.Storage;
2021
...
2122
private async Task<string> GetDocumentsContentsAsync()
@@ -50,6 +51,7 @@ private async Task GetFilesInFolderAsync(StorageFolder folder, StringBuilder out
5051
The following example takes the `GetFilesInFolderAsync` method from the previous example and adds the ability to retrieve the file size and date modified for each file. The example uses the [BasicProperties](/uwp/api/windows.storage.fileproperties.basicproperties) API to retrieve the file size and date modified for each file, formats the file size, and appends the size and date modified to the `StringBuilder` object after each file and folder name.
5152

5253
```csharp
54+
using System.Text;
5355
using Windows.Storage;
5456
using Windows.Storage.FileProperties;
5557
...

0 commit comments

Comments
 (0)