C#实现遍历名为Config文件夹,获取其中所有子文件夹的名字以及其中所有名为AutoBuildConfig.yaml文件中对应的releaseID和buildSystem的value值,将这些数据保存到数据库
时间: 2024-09-22 12:06:09 浏览: 35
verdaccio的配置文件config.yaml
在C#中,你可以使用`DirectoryInfo`类来遍历文件夹,`FileInfo`类来检查文件名,然后利用`YAML`库解析`AutoBuildConfig.yaml`文件的内容。最后,通过`ADO.NET`或者Entity Framework等技术将数据保存到数据库。以下是一个简单的步骤概述:
1. 引入必要的命名空间:
```csharp
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Data.SqlClient; // 或者其他的数据库访问库
using YamlDotNet.RepresentationModel; // 如果使用YAML.NET处理YAML文件
```
2. 定义一个存储结果的数据结构,例如类`ConfigData`:
```csharp
public class ConfigData
{
public string FolderName { get; set; }
public int ReleaseID { get; set; }
public string BuildSystem { get; set; }
}
```
3. 遍历文件夹并读取配置文件:
```csharp
List<ConfigData> configDataList = new List<ConfigData>();
string folderPath = "Config"; // 文件夹路径
DirectoryInfo dir = new DirectoryInfo(folderPath);
foreach (DirectoryInfo subFolder in dir.GetDirectories())
{
string configFile = Path.Combine(subFolder.FullName, "AutoBuildConfig.yaml");
if (File.Exists(configFile))
{
using var stream = File.OpenText(configFile);
var yaml = YAML.Load(stream); // 使用YAML.NET
if (yaml != null)
{
var releaseNode = yaml.Children.FirstOrDefault(c => c.Name == "releaseID");
var buildSystemNode = yaml.Children.FirstOrDefault(c => c.Name == "buildSystem");
if (releaseNode is not null && buildSystemNode is not null)
{
ConfigData data = new ConfigData
{
FolderName = subFolder.Name,
ReleaseID = int.Parse(releaseNode.Value),
BuildSystem = buildSystemNode.Value
};
configDataList.Add(data);
}
}
}
}
```
4. 将数据保存到数据库:
```csharp
// 假设已经有一个SqlConnection连接
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
foreach (var configData in configDataList)
{
string query = $"INSERT INTO ConfigData (FolderName, ReleaseID, BuildSystem) VALUES (@FolderName, @ReleaseID, @BuildSystem)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@FolderName", configData.FolderName);
command.Parameters.AddWithValue("@ReleaseID", configData.ReleaseID);
command.Parameters.AddWithValue("@BuildSystem", configData.BuildSystem);
command.ExecuteNonQuery();
}
}
```
阅读全文