主頁 > .NET開發 > C#,來一個用文本存物件的輪子

C#,來一個用文本存物件的輪子

2020-10-03 22:34:06 .NET開發

  前言

    看了大家都在造輪子,我也要寫一個站點自用了,沒有資料庫怎么辦,又不想用Sqlite,所以自己造吧,大不了就是都檔案到記憶體,然后記憶體到檔案,

  正文

    對于這種操作,無非就是反射一下屬性,然后通過物件和屬性進行更新,當然EF也有這樣的功能,不過對Model而言太臃腫了,這里就不用了,

  上代碼

    

  1     /// <summary>
  2     /// 檔案系統資料庫
  3     /// 主鍵Attribute [Key],支持主鍵比較
  4     /// </summary>
  5     /// <typeparam name="T"></typeparam>
  6     public class FileDbHelper<T> where T : class
  7     {
  8         private static List<T> dataList = new List<T>();
  9         private static string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", typeof(T).Name + ".mydb");
 10         private static JavaScriptSerializer js = new JavaScriptSerializer();
 11 
 12         static FileDbHelper()
 13         {
 14             string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data");
 15             if (!Directory.Exists(dir))
 16             {
 17                 Directory.CreateDirectory(dir);
 18             }
 19 
 20             string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", typeof(T).Name + ".mydb");
 21             if (File.Exists(savePath))
 22             {
 23                 string[] lines = File.ReadAllLines(savePath, Encoding.UTF8);
 24                 foreach (var line in lines)
 25                 {
 26                     if (!string.IsNullOrEmpty(line))
 27                     {
 28                         try
 29                         {
 30                             dataList.Add(js.Deserialize<T>(line));
 31                         }
 32                         catch { }
 33                     }
 34                 }
 35             }
 36         }
 37 
 38         public static void Add(T model)
 39         {
 40             lock (dataList)
 41             {
 42                 dataList.Add(model);
 43                 SaveFile();
 44             }
 45         }
 46 
 47         public static void AddList(List<T> list)
 48         {
 49             lock (dataList)
 50             {
 51                 dataList.AddRange(list);
 52                 SaveFile();
 53             }
 54         }
 55 
 56         public static void AddOrUpdate(T model, params string[] args)
 57         {
 58             lock (dataList)
 59             {
 60                 List<FileDbInfo> infoList = FindKeyDbList(model);
 61                 T equalModel = CheckKeyEqual(model, infoList);
 62                 if (equalModel == null)
 63                 {
 64                     Add(model);
 65                 }
 66                 else
 67                 {
 68                     Update(equalModel, model, args);
 69                 }
 70 
 71                 SaveFile();
 72             }
 73         }
 74 
 75         public static T QueryInfo(T model, params string[] args)
 76         {
 77             lock (dataList)
 78             {
 79                 List<FileDbInfo> infoList = FindArgsDbList(model, args);
 80                 T equalModel = CheckKeyEqual(model, infoList, args);
 81 
 82                 return equalModel;
 83             }
 84         }
 85 
 86         public static List<T> QueryList(int page, int pageSize, T model, params string[] args)
 87         {
 88             lock (dataList)
 89             {
 90                 List<FileDbInfo> infoList = FindArgsDbList(model, args);
 91                 List<T> equalList = CheckArgsEqualList(model, infoList, args);
 92 
 93                 return equalList.Skip(pageSize * (page - 1)).Take(pageSize).ToList();
 94             }
 95         }
 96 
 97         private static void Update(T oldModel, T newModel, string[] args)
 98         {
 99             List<string> keyList = ReadKeyName();
100             foreach (PropertyInfo pInfo in newModel.GetType().GetProperties())
101             {
102                 if (args.Length > 0)
103                 {
104                     if (!args.ToList().Contains(pInfo.Name))
105                     {
106                         Object new_value = https://www.cnblogs.com/Supperlitt/archive/2020/10/03/pInfo.GetValue(newModel, null);
107                         pInfo.SetValue(oldModel, new_value, null);
108                     }
109                 }
110                 else
111                 {
112                     if (!keyList.Contains(pInfo.Name))
113                     {
114                         Object new_value = https://www.cnblogs.com/Supperlitt/archive/2020/10/03/pInfo.GetValue(newModel, null);
115                         pInfo.SetValue(oldModel, new_value, null);
116                     }
117                 }
118             }
119         }
120 
121         private static T CheckKeyEqual(T model, List<FileDbInfo> infoList, string[] args = null)
122         {
123             foreach (var item in dataList)
124             {
125                 bool is_equal = true;
126                 foreach (var info in infoList)
127                 {
128                     if (args == null || (args != null && args.ToList().Contains(info.key)))
129                     {
130                         if (ReadString(model, info.key) != ReadString(item, info.key))
131                         {
132                             is_equal = false;
133                             break;
134                         }
135                     }
136                 }
137 
138                 if (is_equal)
139                 {
140                     return item;
141                 }
142             }
143 
144             return null;
145         }
146 
147         private static List<T> CheckArgsEqualList(T model, List<FileDbInfo> infoList, string[] args = null)
148         {
149             List<T> result = new List<T>();
150             foreach (var item in dataList)
151             {
152                 bool is_equal = true;
153                 foreach (var info in infoList)
154                 {
155                     if (args == null || (args != null && args.ToList().Contains(info.key)))
156                     {
157                         if (ReadString(model, info.key) != ReadString(item, info.key))
158                         {
159                             is_equal = false;
160                             break;
161                         }
162                     }
163                 }
164 
165                 if (is_equal)
166                 {
167                     result.Add(item);
168                 }
169             }
170 
171             return result;
172         }
173 
174         private static List<FileDbInfo> FindKeyDbList(T model, params string[] args)
175         {
176             List<string> keyList = ReadKeyName();
177             var infoList = new List<FileDbInfo>();
178             foreach (var key in keyList)
179             {
180                 if (args == null || (args != null && args.ToList().Contains(key)))
181                 {
182                     infoList.Add(new FileDbInfo(key, ReadString(model, key)));
183                 }
184             }
185 
186             return infoList;
187         }
188 
189         private static List<FileDbInfo> FindArgsDbList(T model, params string[] args)
190         {
191             List<string> keyList = ReadArgsName();
192             var infoList = new List<FileDbInfo>();
193             foreach (var key in keyList)
194             {
195                 if (args == null || (args != null && args.ToList().Contains(key)))
196                 {
197                     infoList.Add(new FileDbInfo(key, ReadString(model, key)));
198                 }
199             }
200 
201             return infoList;
202         }
203 
204         private static List<string> ReadKeyName()
205         {
206             List<string> keyList = new List<string>();
207             foreach (var pInfo in typeof(T).GetProperties())
208             {
209                 foreach (var attr in pInfo.GetCustomAttributes(false))
210                 {
211                     if (attr.GetType() == typeof(KeyAttribute))
212                     {
213                         keyList.Add(pInfo.Name);
214                     }
215                 }
216             }
217 
218             if (keyList.Count == 0)
219             {
220                 throw new Exception("未定義主鍵,通過設定注解來添加主鍵[Key],目前只支持int和string");
221             }
222 
223             return keyList;
224         }
225 
226         private static List<string> ReadArgsName()
227         {
228             List<string> keyList = new List<string>();
229             foreach (var pInfo in typeof(T).GetProperties())
230             {
231                 keyList.Add(pInfo.Name);
232             }
233 
234             return keyList;
235         }
236 
237         private static string ReadString(T model, string key_name)
238         {
239             PropertyInfo propertyInfo = model.GetType().GetProperty(key_name);
240             object obj = propertyInfo.GetValue(model, null);
241             if (propertyInfo.PropertyType == typeof(int))
242             {
243                 return obj.ToString();
244             }
245             else if (propertyInfo.PropertyType == typeof(string))
246             {
247                 return obj.ToString();
248             }
249             else
250             {
251                 return obj.ToString();
252             }
253         }
254 
255         private static void SaveFile()
256         {
257             StringBuilder content = new StringBuilder();
258             foreach (var item in dataList)
259             {
260                 content.AppendLine(js.Serialize(item));
261             }
262 
263             File.WriteAllText(savePath, content.ToString(), new UTF8Encoding(false));
264         }
265     }
266 
267     public class FileDbInfo
268     {
269         public FileDbInfo(string key, string str_value)
270         {
271             this.key = key;
272             this.str_value =https://www.cnblogs.com/Supperlitt/archive/2020/10/03/ str_value;
273         }
274 
275         public string key { get; set; }
276 
277         public string str_value { get; set; }
278     }
279 
280     public class KeyAttribute : Attribute { }
281 }

  使用方式,

public class UserInfo2
    {
        [Key]
        public string name { get; set; }

        public string pwd { get; set; }

        public int age { get; set; }

        public string info { get; set; }
    }
        // 新增資料
       FileDbHelper<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test1", pwd = "12341", age = 10 }); FileDbHelper<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test2", pwd = "12342", age = 10 }); FileDbHelper<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test3", pwd = "12343", age = 11 }); FileDbHelper<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test4", pwd = "12344", age = 12 }); FileDbHelper<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test5", pwd = "12345", age = 10 });
       // 查詢集合,條件查詢
var list = FileDbHelper<UserInfo2>.QueryList(1, 10, new UserInfo2() { age = 10 }, "age");
// 單個物件,條件查詢
var model = FileDbHelper<UserInfo2>.QueryInfo(new UserInfo2() { age = 12 }, "age");
// 修改所有值 model.info
= "hehe"; FileDbHelper<UserInfo2>.AddOrUpdate(model);
// 修改指定的值 FileDbHelper
<UserInfo2>.AddOrUpdate(new UserInfo2() { name = "test1", age = 12 }, "age"); var model2 = FileDbHelper<UserInfo2>.QueryInfo(model);

總結:偉大出自平凡,

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/152711.html

標籤:.NET技术

上一篇:C#,來一個用文本存物件的輪子

下一篇:OPCUA如何監聽一個服務器的事件?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more