c#读取json文件操作json文件

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
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
 
namespace Config
{
    public class Configs
    {
        public static string GetConnectionValue(string Config)
        {
            //手动读取配置
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.AddJsonFile(GetAbsolutePath("config/sqlserver.json"), optional: false, reloadOnChange: false);
            IConfigurationRoot config = configBuilder.Build();
            return config.GetSection("connectionStrings:"+Config).Value;
        }
 
        public static string GetConfigSettingsValue(string Key, string KeyTxt)
        {
            //手动读取配置
            ConfigurationBuilder configBuilder = new ConfigurationBuilder();
            configBuilder.AddJsonFile(GetAbsolutePath("config/settings.json"), optional: false, reloadOnChange: false);
            IConfigurationRoot config = configBuilder.Build();
 
            return KeyTxt!="" ? config.GetSection(Key+":"+KeyTxt).Value : config.GetSection(Key).Value;
        }
 
        #region 扩展
        /// <summary>
        /// 获取文件的绝对路径,针对window程序和web程序都可使用
        /// </summary>
        /// <param name="relativePath">相对路径地址</param>
        /// <returns>绝对路径地址</returns>
        public static string GetAbsolutePath(string relativePath)
        {
            string path = Directory.GetCurrentDirectory();
            IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(path).AddJsonFile("appsettings.json").Build();
 
            if (string.IsNullOrEmpty(relativePath))
            {
                return "";
            }
            relativePath = relativePath.Replace("/", "\\");
            if (relativePath[0] == '\\')
            {
                relativePath = relativePath.Remove(0, 1);
            }
            //使用path获取当前应用程序集的执行目录的上级的上级目录
 
            string dir = ToBool(configuration["Debug"]) ? Path.GetFullPath("../../../") : path;
 
            return Path.Combine(dir, relativePath);
        }
 
        public static bool SaveJson(Dictionary<string, object> sectionInfo, string configFileName)
        {
            if (sectionInfo.Count==0)
                return false;
 
            try
            {
                var filePath = GetAbsolutePath(configFileName);
                JObject jsonObject;
 
                if (File.Exists(filePath))
                {
                    using (StreamReader file = new StreamReader(filePath))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            jsonObject = JObject.Parse(ToJson(JToken.ReadFrom(reader)));
                        }
                    }
                }
                else
                {
                    jsonObject = new JObject();
                }
 
                foreach (var key in sectionInfo.Keys)
                {
                    jsonObject[key] = JObject.FromObject(sectionInfo[key]);
                }
 
                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer)
                {
                    Formatting = Formatting.Indented,//格式化缩进
                    Indentation = 4,  //缩进四个字符
                    IndentChar = ' '  //缩进的字符是空格
                })
                {
                    jsonObject.WriteTo(jsonwriter);
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion
 
        #region ToBool
 
        /// <summary>
        /// 转换为布尔值
        /// </summary>
        /// <param name="data">数据</param>
        public static bool ToBool(object data)
        {
            if (data == null)
                return false;
            bool? value = GetBool(data);
            if (value != null)
                return value.Value;
            bool result;
            return bool.TryParse(data.ToString(), out result) && result;
        }
 
        /// <summary>
        /// 获取布尔值
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        private static bool? GetBool(object data)
        {
            switch (data.ToString().Trim().ToLower())
            {
                case "0":
                    return false;
                case "1":
                    return true;
                case "是":
                    return true;
                case "否":
                    return false;
                case "yes":
                    return true;
                case "no":
                    return false;
                default:
                    return null;
            }
        }
 
        #endregion
        #region ToJson
        /// <summary>
        /// 转成json字串
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static string ToJson(object obj)
        {
            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        #endregion
    }
}

  

posted @   MakeGod  阅读(5732)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示