配色: 字号:
C#实现文件数据库
2016-09-14 | 阅:  转:  |  分享 
  
C#实现文件数据库
如果你需要一个简单的磁盘文件索引数据库,这篇文章可以帮助你。

文件数据库描述:

每个文档对象保存为一个独立文件,例如一篇博客。
文件内容序列化支持XML或JSON。
支持基本的CRUD操作。
文件数据库抽象类实现
ViewCode
XML文件数据库实现
复制代码
1///
2///XML文件数据库
3///

4publicclassXmlDatabase:FileDatabase
5{
6///
7///XML文件数据库
8///

9///数据库文件所在目录
10publicXmlDatabase(stringdirectory)
11:base(directory)
12{
13FileExtension=@"xml";
14}
15
16///
17///将指定的文档对象序列化至字符串
18///

19///指定的文档对象
20///
21///文档对象序列化后的字符串
22///

23protectedoverridestringSerialize(objectvalue)
24{
25if(value==null)
26thrownewArgumentNullException("value");
27
28using(StringWriterWithEncodingsw=newStringWriterWithEncoding(Encoding.UTF8))
29{
30XmlSerializerserializer=newXmlSerializer(value.GetType());
31seriawww.wang027.comlizer.Serialize(sw,value);
32returnsw.ToString();
33}
34}
35
36///
37///将字符串反序列化成文档对象
38///

39///文档类型
40///字符串
41///
42///文档对象
43///

44protectedoverrideTDocumentDeserialize(stringdata)
45{
46if(string.IsNullOrEmpty(data))
47thrownewArgumentNullException("data");
48
49using(StringReadersr=newStringReader(data))
50{
51XmlSerializerserializer=newXmlSerializer(typeof(TDocument));
52return(TDocument)serializer.Deserialize(sr);
53}
54}
55}
复制代码
JSON文件数据库实现
复制代码
1///
2///JSON文件数据库
3///

4publicclassJsonDatabase:FileDatabase
5{
6///
7///JSON文件数据库
8///

9///数据库文件所在目录
10publicJsonDatabase(stringdirectory)
11:base(directory)
12{
13FileExtension=@"json";
14}
15
16///
17///将指定的文档对象序列化至字符串
18///

19///指定的文档对象
20///
21///文档对象序列化后的字符串
22///

23protectedoverridestringSerialize(objectvalue)
24{
25if(value==null)
26thrownewArgumentNullException("value");
27
28returnJsonConvert.SerializeObject(value,OutputIndent);
29}
30
31///
32///将字符串反序列化成文档对象
33///

34///文档类型
35///字符串
36///
37///文档对象
38///

39protectedoverrideTDocumentDeserialize(stringdata)
40{
41if(string.IsNullOrEmpty(data))
42thrownewArgumentNullException("data");
43
44returnJsonConvert.DeserializeObject(data);
45}
46}
复制代码
TestDouble
复制代码
1[Serializable]
2publicclassCat
3{
4publicCat()
5{
6Id=ObjectId.NewObjectId().ToString();
7}
8
9publicCat(stringid)
10{
11Id=id;
12}
13
14publicstringName{get;set;}
15publicintLegs{get;set;}
16
17publicstringId{get;set;}
18
19publicoverridestringToString()
20{
21returnstring.Format("DocumentId={0},Name={1},Legs={2}",Id,Name,Legs);
22}
23}
复制代码
使用举例
复制代码
1classProgram
2{
3staticvoidMain(string[]args)
4{
5TestJsonDatabase();
6TestXmlDatabase();
7
8Console.ReadKey();
9}
10
11privatestaticvoidTestJsonDatabase()
12{
13JsonDatabasedb=newJsonDatabase(@"C:\tmp");
14db.OutputIndent=true;
15
16Catorigin=newCat(){Name="Garfield",Legs=4};
17db.Save(origin);
18
19db.Save(origin.Id,origin);
20db.Delete(origin.Id);
21}
22
23privatestaticvoidTestXmlDatabase()
24{
25XmlDatabasedb=newXmlDatabase(@"C:\tmp");
26db.OutputIndent=true;
27
28Catorigin=newCat(){Name="Garfield",Legs=4};
29db.Save(origin);
30
31db.Save(origin.Id,origin);
32db.Delete(origin.Id);
33}
34}
献花(0)
+1
(本文系thedust79首藏)