public void Reload() { var dbName = _configurationRoot.GetSection("SqliteConnection").Value; var dirPath = Path.GetDirectoryName(dbName.Substring(dbName.IndexOf("=")+1)); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } dbName = dbName.Substring(0, dbName.LastIndexOf(@"\") == -1 ? 0 : dbName.LastIndexOf(@"\") + 1); dbName = $"{dbName}MigrateDb_{DateTime.Now.ToString("yyyyMMddHHmmss")}.db"; MigrateDbContext.DbName = dbName; string json = File.ReadAllText("appsettings.json"); var setting = JsonSerializer.Deserialize<SettingProperties>(json); setting.SqliteConnection = dbName; var serialize = JsonSerializer.Serialize(setting); using var stream = new FileStream("appsettings.json", FileMode.Create, FileAccess.ReadWrite); using StreamWriter streamWriter = new StreamWriter(stream); streamWriter.WriteLine(serialize); _context?.Dispose(); _context = new MigrateDbContext(); _context.Database.EnsureCreatedAsync(); } 优化这段代码
时间: 2024-02-14 16:18:16 浏览: 152
livereload_2_1_0_-.zip
首先,我们可以把一些重复的代码提取出来,比如获取数据库名和创建目录的部分,可以写成一个单独的方法,代码如下:
```csharp
private string GetDbNameAndCreateDirectory(string connectionString)
{
var dbName = connectionString.Substring(connectionString.IndexOf("=") + 1);
var dirPath = Path.GetDirectoryName(dbName);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
dbName = dbName.Substring(0, dbName.LastIndexOf(@"\") == -1 ? 0 : dbName.LastIndexOf(@"\") + 1);
dbName = $"{dbName}MigrateDb_{DateTime.Now:yyyyMMddHHmmss}.db";
return dbName;
}
```
然后,我们可以将获取连接字符串和更新配置文件的部分也提取出来,写成一个方法:
```csharp
private void UpdateConnectionString(string newConnectionString)
{
string json = File.ReadAllText("appsettings.json");
var setting = JsonSerializer.Deserialize<SettingProperties>(json);
setting.SqliteConnection = newConnectionString;
var serialize = JsonSerializer.Serialize(setting);
using var stream = new FileStream("appsettings.json", FileMode.Create, FileAccess.ReadWrite);
using StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.WriteLine(serialize);
}
```
最后,我们可以将 Reload 方法中的代码进行重构,将每个步骤都提取出来,使代码更加清晰易懂,代码如下:
```csharp
public void Reload()
{
var connectionString = _configurationRoot.GetSection("SqliteConnection").Value;
var newConnectionString = GetDbNameAndCreateDirectory(connectionString);
UpdateConnectionString(newConnectionString);
_context?.Dispose();
_context = new MigrateDbContext();
_context.Database.EnsureCreatedAsync();
}
```
这样,我们就将代码进行了优化,使其更加清晰易懂、易于维护。
阅读全文