| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- using System.Text;
- using Newtonsoft.Json;
- namespace Vbdsm.Common
- {
- public class FileHelper
- {
- public static T? ReadFileInfo<T>(string fileName) where T : new()
- {
- var str = ReadFileInfo(fileName);
- return Str2Obj<T>(str);
- }
- public static string ReadFileInfo(string fileName, string path = "Data")
- {
- string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{path}\\{fileName}.json");
- StringBuilder sb = new StringBuilder();
- if (File.Exists(filePath)) //文件存在
- {
- try
- {
- FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
- StreamReader reader = new StreamReader(fs, Encoding.UTF8);
- while (reader.ReadLine() is { } line)
- {
- sb.Append(line);
- }
- reader.Close();
- fs.Close();
- }
- catch
- {
- // ignored
- }
- }
- return sb.ToString();
- }
- public static void SaveFileInfo(object obj, string fileName)
- {
- string str = Obj2Str(obj);
- SaveFileInfo(str, fileName);
- }
- public static void SaveFileInfo(string contents, string fileName)
- {
- string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Data");
- if (!Directory.Exists(path))
- {
- Directory.CreateDirectory(path);
- }
- string filePath = $"{path}\\{fileName}.json";
- File.WriteAllText(filePath, contents);
- }
- public static T? Str2Obj<T>(string str) where T : new()
- {
- if (!string.IsNullOrEmpty(str))
- {
- try
- {
- return JsonConvert.DeserializeObject<T>(str);
- }
- catch //(Exception e)
- {
- return default;
- }
- }
- return default;
- }
- public static string Obj2Str(object obj)
- {
- return JsonConvert.SerializeObject(obj, Formatting.Indented);
- }
- }
- }
|