-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualFileExtensions.cs
More file actions
405 lines (356 loc) · 19.6 KB
/
VirtualFileExtensions.cs
File metadata and controls
405 lines (356 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
using System.Buffers;
using System.Text;
namespace Ramstack.FileSystem;
/// <summary>
/// Provides extension methods for the <see cref="VirtualFile"/> class.
/// </summary>
public static class VirtualFileExtensions
{
/// <summary>
/// Asynchronously returns a <see cref="StreamReader"/> with <see cref="Encoding.UTF8"/>
/// character encoding that reads from the specified text file.
/// </summary>
/// <param name="file">The file to get the <see cref="StreamReader"/> for.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation.
/// The result is a <see cref="StreamReader"/> that reads from the text file.
/// </returns>
public static ValueTask<StreamReader> OpenTextAsync(this VirtualFile file, CancellationToken cancellationToken = default) =>
file.OpenTextAsync(encoding: null, cancellationToken);
/// <summary>
/// Asynchronously returns a <see cref="StreamReader"/> with the specified character encoding
/// that reads from the specified text file.
/// </summary>
/// <param name="file">The file to get the <see cref="StreamReader"/> for.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation.
/// The result is a <see cref="StreamReader"/> that reads from the text file.
/// </returns>
public static async ValueTask<StreamReader> OpenTextAsync(this VirtualFile file, Encoding? encoding, CancellationToken cancellationToken = default)
{
var stream = await file.OpenReadAsync(cancellationToken).ConfigureAwait(false);
return new StreamReader(stream, encoding!);
}
/// <summary>
/// Asynchronously writes the specified content to a file. If the file exists, an exception will be thrown.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="stream">A <see cref="Stream"/> containing the content to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAsync(this VirtualFile file, Stream stream, CancellationToken cancellationToken = default) =>
file.WriteAsync(stream, overwrite: false, cancellationToken);
/// <summary>
/// Asynchronously reads all the text in the current file.
/// </summary>
/// <param name="file">The file from which to read the entire text content.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation,
/// containing the full text from the current file.
/// </returns>
public static ValueTask<string> ReadAllTextAsync(this VirtualFile file, CancellationToken cancellationToken = default) =>
ReadAllTextAsync(file, encoding: null, cancellationToken);
/// <summary>
/// Asynchronously reads all the text in the current file with the specified encoding.
/// </summary>
/// <param name="file">The file from which to read the entire text content.</param>
/// <param name="encoding">The encoding applied to the contents.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation,
/// containing the full text from the current file.
/// </returns>
public static async ValueTask<string> ReadAllTextAsync(this VirtualFile file, Encoding? encoding, CancellationToken cancellationToken = default)
{
//
// Use a manual read loop since .NET 6 lacks a StreamReader.ReadToEndAsync overload that accepts a CancellationToken.
// This ensures the operation remains responsive to cancellation requests.
//
const int BufferSize = 4096;
// ReSharper disable once UseAwaitUsing
using var stream = await file.OpenReadAsync(cancellationToken).ConfigureAwait(false);
var reader = new StreamReader(stream, encoding ??= Encoding.UTF8);
var buffer = (char[]?)null;
try
{
cancellationToken.ThrowIfCancellationRequested();
buffer = ArrayPool<char>.Shared.Rent(encoding.GetMaxCharCount(BufferSize));
var sb = new StringBuilder();
while (true)
{
var count = await reader
.ReadAsync(new Memory<char>(buffer), cancellationToken)
.ConfigureAwait(false);
if (count == 0)
return sb.ToString();
sb.Append(buffer.AsSpan(0, count));
}
}
finally
{
reader.Dispose();
if (buffer is not null)
ArrayPool<char>.Shared.Return(buffer);
}
}
/// <summary>
/// Asynchronously reads all lines of the current file.
/// </summary>
/// <param name="file">The file to read from.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation,
/// containing an array of all lines in the current file.
/// </returns>
public static ValueTask<string[]> ReadAllLinesAsync(this VirtualFile file, CancellationToken cancellationToken = default) =>
ReadAllLinesAsync(file, encoding: null, cancellationToken);
/// <summary>
/// Asynchronously reads all lines of the current file with the specified encoding.
/// </summary>
/// <param name="file">The file to read from.</param>
/// <param name="encoding">The encoding applied to the contents.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation,
/// containing an array of all lines in the current file.
/// </returns>
public static async ValueTask<string[]> ReadAllLinesAsync(this VirtualFile file, Encoding? encoding, CancellationToken cancellationToken = default)
{
var stream = await file.OpenReadAsync(cancellationToken).ConfigureAwait(false);
using var reader = new StreamReader(stream, encoding!);
var list = new List<string>();
while (await reader.ReadLineAsync().ConfigureAwait(false) is { } line)
{
cancellationToken.ThrowIfCancellationRequested();
list.Add(line);
}
return list.ToArray();
}
/// <summary>
/// Asynchronously reads the entire contents of the current file into a byte array.
/// </summary>
/// <param name="file">The file to read from.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation,
/// containing an array of the file's bytes.
/// </returns>
public static async ValueTask<byte[]> ReadAllBytesAsync(this VirtualFile file, CancellationToken cancellationToken = default)
{
// ReSharper disable once UseAwaitUsing
using var stream = await file.OpenReadAsync(cancellationToken).ConfigureAwait(false);
var length = GetStreamLength(stream);
if (length > Array.MaxLength)
throw new IOException("The file is too large.");
var task = length <= 0
? ReadAllBytesUnknownLengthImplAsync(stream, cancellationToken)
: ReadAllBytesImplAsync(stream, cancellationToken);
return await task.ConfigureAwait(false);
static async ValueTask<byte[]> ReadAllBytesImplAsync(Stream stream, CancellationToken cancellationToken)
{
var bytes = new byte[stream.Length];
var index = 0;
do
{
var count = await stream.ReadAsync(bytes.AsMemory(index), cancellationToken).ConfigureAwait(false);
if (count == 0)
Error_EndOfStream();
index += count;
}
while (index < bytes.Length);
return bytes;
}
static async ValueTask<byte[]> ReadAllBytesUnknownLengthImplAsync(Stream stream, CancellationToken cancellationToken)
{
var bytes = ArrayPool<byte>.Shared.Rent(512);
var total = 0;
while (true)
{
if (total == bytes.Length)
bytes = ResizeBuffer(bytes);
var count = await stream
.ReadAsync(bytes.AsMemory(total), cancellationToken)
.ConfigureAwait(false);
if (count == 0)
{
var result = bytes.AsSpan(0, total).ToArray();
ArrayPool<byte>.Shared.Return(bytes);
return result;
}
total += count;
}
static byte[] ResizeBuffer(byte[] oldArray)
{
var length = (uint)oldArray.Length * 2;
if (length > (uint)Array.MaxLength)
length = (uint)Math.Max(Array.MaxLength, oldArray.Length + 1);
var newArray = ArrayPool<byte>.Shared.Rent((int)length);
oldArray.AsSpan().TryCopyTo(newArray);
var rented = oldArray;
oldArray = newArray;
ArrayPool<byte>.Shared.Return(rented);
return oldArray;
}
}
static long GetStreamLength(Stream stream)
{
try
{
if (stream.CanSeek)
return stream.Length;
}
catch
{
// skip
}
return 0;
}
static void Error_EndOfStream() =>
throw new EndOfStreamException();
}
/// <summary>
/// Asynchronously writes the specified string to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAllTextAsync(this VirtualFile file, string contents, CancellationToken cancellationToken = default) =>
WriteAllTextAsync(file, contents.AsMemory(), encoding: null, cancellationToken);
/// <summary>
/// Asynchronously writes the specified string to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAllTextAsync(this VirtualFile file, string contents, Encoding? encoding, CancellationToken cancellationToken = default) =>
WriteAllTextAsync(file, contents.AsMemory(), encoding, cancellationToken);
/// <summary>
/// Asynchronously writes the specified string to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAllTextAsync(this VirtualFile file, ReadOnlyMemory<char> contents, CancellationToken cancellationToken = default) =>
WriteAllTextAsync(file, contents, encoding: null, cancellationToken);
/// <summary>
/// Asynchronously writes the specified string to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static async ValueTask WriteAllTextAsync(this VirtualFile file, ReadOnlyMemory<char> contents, Encoding? encoding, CancellationToken cancellationToken = default)
{
await using var stream = await file.OpenWriteAsync(cancellationToken).ConfigureAwait(false);
await using var writer = new StreamWriter(stream, encoding!);
await writer.WriteAsync(contents, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously writes the specified lines to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAllLinesAsync(this VirtualFile file, IEnumerable<string> contents, CancellationToken cancellationToken = default) =>
WriteAllLinesAsync(file, contents, encoding: null, cancellationToken);
/// <summary>
/// Asynchronously writes the specified lines to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="contents">The contents to write to the file.</param>
/// <param name="encoding">The encoding to apply to the string.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static async ValueTask WriteAllLinesAsync(this VirtualFile file, IEnumerable<string> contents, Encoding? encoding, CancellationToken cancellationToken = default)
{
await using var stream = await file.OpenWriteAsync(cancellationToken).ConfigureAwait(false);
await using var writer = new StreamWriter(stream, encoding, bufferSize: -1, leaveOpen: false);
foreach (var line in contents)
await writer.WriteLineAsync(line).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously writes the specified byte array to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="bytes">The bytes to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask WriteAllBytesAsync(this VirtualFile file, byte[] bytes, CancellationToken cancellationToken = default) =>
WriteAllBytesAsync(file, bytes.AsMemory(), cancellationToken);
/// <summary>
/// Asynchronously writes the specified byte array to the current file. If the file already exists, it is truncated and overwritten.
/// </summary>
/// <param name="file">The file to write to.</param>
/// <param name="bytes">The bytes to write to the file.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static async ValueTask WriteAllBytesAsync(this VirtualFile file, ReadOnlyMemory<byte> bytes, CancellationToken cancellationToken = default)
{
await using var stream = await file.OpenWriteAsync(cancellationToken).ConfigureAwait(false);
await stream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously copies the file to the specified destination path.
/// </summary>
/// <param name="file">The source <see cref="VirtualFile"/> to copy from.</param>
/// <param name="destinationPath">The path of the destination file. This cannot be a directory.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous operation.
/// </returns>
public static ValueTask CopyToAsync(this VirtualFile file, string destinationPath, CancellationToken cancellationToken = default) =>
file.CopyToAsync(destinationPath, overwrite: false, cancellationToken);
/// <summary>
/// Asynchronously copies the contents of the current <see cref="VirtualFile"/> to the specified destination <see cref="VirtualFile"/>.
/// </summary>
/// <param name="file">The source <see cref="VirtualFile"/> to copy from.</param>
/// <param name="destination">The destination <see cref="VirtualFile"/> where the contents will be copied to.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="ValueTask"/> that represents the asynchronous copy operation.
/// </returns>
public static ValueTask CopyToAsync(this VirtualFile file, VirtualFile destination, CancellationToken cancellationToken = default) =>
file.CopyToAsync(destination, overwrite: false, cancellationToken);
/// <summary>
/// Asynchronously returns the size of the specified file in bytes.
/// </summary>
/// <param name="file">The file to get the size of.</param>
/// <param name="cancellationToken">An optional cancellation token to cancel the operation.</param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> representing the asynchronous operation.
/// The result is the size of the specified file in bytes, or <c>-1</c> if the file does not exist.
/// </returns>
public static async ValueTask<long> GetLengthAsync(this VirtualFile file, CancellationToken cancellationToken = default)
{
var properties = await file.GetPropertiesAsync(cancellationToken).ConfigureAwait(false);
return properties.Length;
}
}