1+ static class IoHelpers
2+ {
3+ static readonly UTF8Encoding Utf8 = new ( true , true ) ;
4+
5+ public static void DeleteIfEmpty ( string path )
6+ {
7+ var info = new FileInfo ( path ) ;
8+ if ( info . Exists && info . Length == 0 )
9+ {
10+ info . Delete ( ) ;
11+ }
12+ }
13+
14+ public static void MoveToStart ( this Stream stream )
15+ {
16+ if ( stream . CanSeek )
17+ {
18+ stream . Position = 0 ;
19+ }
20+ }
21+
22+ static FileStream OpenWrite ( string path )
23+ {
24+ return new ( path , FileMode . Create , FileAccess . Write , FileShare . Read , bufferSize : 4096 , useAsync : true ) ;
25+ }
26+
27+ public static FileStream OpenRead ( string path )
28+ {
29+ return new ( path , FileMode . Open , FileAccess . Read , FileShare . Read , bufferSize : 4096 , useAsync : true ) ;
30+ }
31+
32+ public static long Length ( string file )
33+ {
34+ return new FileInfo ( file ) . Length ;
35+ }
36+
37+ public static async Task < string > ReadString ( this Stream stream )
38+ {
39+ stream . MoveToStart ( ) ;
40+ using var reader = new StreamReader ( stream ) ;
41+ return await reader . ReadToEndAsync ( ) ;
42+ }
43+
44+ static async Task < string > ReadStringWithFixedLines ( this Stream stream )
45+ {
46+ var stringValue = await stream . ReadString ( ) ;
47+ var builder = new StringBuilder ( stringValue ) ;
48+ builder . FixNewlines ( ) ;
49+ return builder . ToString ( ) ;
50+ }
51+
52+ #if NETSTANDARD2_1 || NET5_0_OR_GREATER
53+
54+ public static Task WriteText ( string path , string text )
55+ {
56+ return File . WriteAllTextAsync ( path , text , Utf8 ) ;
57+ }
58+
59+ public static async Task < string > ReadStringWithFixedLines ( string path )
60+ {
61+ await using var stream = OpenRead ( path ) ;
62+ return await stream . ReadStringWithFixedLines ( ) ;
63+ }
64+
65+ public static async Task WriteStream ( string path , Stream stream )
66+ {
67+ if ( stream is FileStream fileStream )
68+ {
69+ File . Copy ( fileStream . Name , path ) ;
70+ return ;
71+ }
72+
73+ await using var targetStream = OpenWrite ( path ) ;
74+ await stream . CopyToAsync ( targetStream ) ;
75+ }
76+
77+ #else
78+
79+ public static async Task WriteText ( string path , string text )
80+ {
81+ var encodedText = Utf8 . GetBytes ( text ) ;
82+
83+ using var stream = OpenWrite ( path ) ;
84+ await stream . WriteAsync ( encodedText , 0 , encodedText . Length ) ;
85+ }
86+
87+ public static async Task WriteStream ( string path , Stream stream )
88+ {
89+ if ( stream is FileStream fileStream )
90+ {
91+ File . Copy ( fileStream . Name , path , true ) ;
92+ return ;
93+ }
94+
95+ using var targetStream = OpenWrite ( path ) ;
96+ await stream . CopyToAsync ( targetStream ) ;
97+ }
98+
99+ public static async Task < string > ReadStringWithFixedLines ( string path )
100+ {
101+ using var stream = OpenRead ( path ) ;
102+ return await stream . ReadStringWithFixedLines ( ) ;
103+ }
104+
105+ #endif
106+ }
0 commit comments