This article will demonstrate how to implement CRUD functionality with JSON file in a project using C# code. This article gives you an idea how you can perform CRUD operations on JSON files and use JSON files as a database.
the classes
the classes
namespace Miniblog.Core.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
public class Post
{
public IList<string> Categories { get; } = new List<string>();
public IList<string> Tags { get; } = new List<string>();
public IList<Comment> Comments { get; } = new List<Comment>();
[Required]
public string Content { get; set; } = string.Empty;
step 2:using System.Text.Json to save the file system(not Newtonsoft.Json)
using System.Text.Json;
Step 3: create FileBlogJsonDataService.cs to implement CRUD interface IBlogService
Serialize and save
public class FileBlogJsonDataService : IBlogService
public async Task SavePost(Post post)
{
if (post is null)
{
throw new ArgumentNullException(nameof(post));
}
var filePath = this.GetFilePath(post);
post.LastModified = DateTime.UtcNow;
// Serialize and save
var serializedData = JsonSerializer.Serialize(post);
await File.WriteAllTextAsync(filePath, serializedData);
if (!this.cache.Contains(post))
{
this.cache.Add(post);
this.SortCache();
}
}
Read and deserialize
private void LoadPosts()
{
if (!Directory.Exists(this.folder))
{
Directory.CreateDirectory(this.folder);
}
// Can this be done in parallel to speed it up?
foreach (var file in Directory.EnumerateFiles(this.folder, "*.json", SearchOption.TopDirectoryOnly))
{
// Read and deserialize
var rawData = File.ReadAllText(file);
var post = JsonSerializer.Deserialize<Post>(rawData);
//LoadCategories(post, doc);
//LoadComments(post, doc);
this.cache.Add(post);
}
}
Step 4:
program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
//new
builder.Services.AddSingleton<IBlogService, FileBlogJsonDataService>();
var app = builder.Build();
读取INI文件
INI 是一种固定标准格式的配置文件,INI配置方法来自 MS-DOS 操作系统。
INI文件是一种简单的配置文件格式,通常用于保存简单的键值对配置。
注释:.ini文件支持单行注释,以分号;或#号开头,指到行尾为止。
INI文件内容如下:
;注释,这是一个示例.ini文件
[Section1]
key1=value1
key2=value2
[Section2]
key3=value3
key4=value4
https://zhuanlan.zhihu.com/p/682922123
Useful links