1- using System . IO ;
1+ using System ;
2+ using System . IO ;
3+ using System . Text . Json ;
4+ using System . Text . Json . Serialization ;
25
36namespace PCL . Core . Model . Files ;
47
@@ -12,11 +15,43 @@ namespace PCL.Core.Model.Files;
1215
1316public static class FileProcesses
1417{
18+ /// <summary>
19+ /// Result: text content of the file.
20+ /// </summary>
1521 public static readonly FileProcess ReadText = ( ( _ , path ) =>
1622 {
1723 if ( path == null ) return null ;
1824 var fs = File . Open ( path , FileMode . OpenOrCreate , FileAccess . Read , FileShare . Read ) ;
1925 var sr = new StreamReader ( fs ) ;
2026 return sr . ReadToEnd ( ) ;
2127 } ) ;
28+
29+ private static readonly JsonSerializerOptions _ParseJsonCreateDefaultOptions = new ( )
30+ {
31+ WriteIndented = true ,
32+ AllowOutOfOrderMetadataProperties = true ,
33+ PropertyNamingPolicy = JsonNamingPolicy . SnakeCaseLower ,
34+ DefaultIgnoreCondition = JsonIgnoreCondition . Never ,
35+ } ;
36+
37+ /// <summary>
38+ /// Result: parsed object as the specified type (nullable)
39+ /// </summary>
40+ /// <typeparam name="TValue">the specified type (must be serializable and have a public default constructor)</typeparam>
41+ /// <param name="createDefault">whether create the file with default values if not exist</param>
42+ public static FileProcess ParseJson < TValue > ( bool createDefault = true ) => ( ( _ , path ) =>
43+ {
44+ if ( path == null ) return null ;
45+ var exist = File . Exists ( path ) ;
46+ using var fs = File . Open ( path , FileMode . OpenOrCreate , FileAccess . ReadWrite , FileShare . Read ) ;
47+ if ( exist )
48+ {
49+ var result = JsonSerializer . Deserialize < TValue > ( fs ) ;
50+ return result ;
51+ }
52+ if ( ! createDefault ) return null ;
53+ var d = Activator . CreateInstance ( typeof ( TValue ) ) ;
54+ JsonSerializer . Serialize ( fs , d , _ParseJsonCreateDefaultOptions ) ;
55+ return d ;
56+ } ) ;
2257}
0 commit comments