从文件调用数据库连接值

Call db connectivity values from a file

我是 c# 的新手,想知道如何从文件中调用值而不是在 class 中对其进行静态硬编码。我知道在 java spring 启动应用程序中我们可以在 application.properties 文件中拥有它。在我的例子中,我将数据库主机名、用户名和密码存储在一个文件中

namespace NunitTestCase
{
    [TestFixture]
    public class Test
    {   
        string query = "SELECT * FROM SYSTEM.ADMIN.EMPLOYEE";
        string host = "vm1.test.app.com";  //want these data in a file
        int port = 5480;
        string dbName = "SYSTEM";
        string userName = "admin";
        string password = "password";
        
        [Test]
        public void TestCase()
        {
            var builder = new ConnectionStringBuilder();
            builder.UserName = userName;
            builder.Password = password;
            builder.Port = port;
            builder.Host = host;
            builder.Database = dbName;

            using (var con = new Connection(builder.ConnectionString))
            {
                con.Open();
                NUnit.Framework.Assert.That(con.State == ConnectionState.Open);
                using (var cmd = new Command(query, con))
                {
                    var rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        for (int i = 0; i < rdr.FieldCount; i++)
                        {
                            object o = null;
                            try
                            {
                                o = rdr.GetValue(i);
                            }
                            catch (Exception ex)
                            {
                                o = ex.Message;
                            }
                            
                            Console.WriteLine(o);
                        }
                    }
                }
                con.Close();
                NUnit.Framework.Assert.That(con.State == ConnectionState.Closed);
            }
        }
    }
}

file.yaml

database:
   host: "vm1.test.app.com"
   port: 5480
   dbName: "SYSTEM"
   userName: "admin"
   password: "password"

如何更改我的代码,而不是硬编码,这些值可以从文件中获取

  1. 传统上,在 .net 中,我们将配置存储在 .json/.xml 文件中,C# 支持 built-in 功能来解析它,但就您使用的 .YAML 而言文件你可以安装库来解析这个文件: YAMLDotNet 并用它来解析。
public class Database {
    public string Host { get; set; }
    public string Port { get; set; }
    public string DbName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
 } 
 public class Configuration
 {
    public Database Database { get; set; }
 }
    var yamlString = File.ReadAllText(@"...\file.yaml");
    
    var deserializer = new DeserializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()).Build();
    
    var config = deserializer.Deserialize<Configuration>(yamlString);
  1. 如果您不想使用任何库,您可以手动解析它,因此创建一个 class 来反映您在 YAML 中的模型,例如:

获取a值的函数属性:

    public string GetValueOfPropertyYaml(string yamlStr) {
        return yamlStr?.Split(":")?.Skip(1)?.FirstOrDefault()?.Trim() ?? string.Empty;
    }

主要代码:

        string[] yamlStringArray = File.ReadAllLines(@"..\file.yaml");
        var config = new Database();
        foreach (var yamlStr in yamlStringArray) {
            if (yamlStr.Contains("host:")) {
                config.Host = GetValueOfPropertyYaml(yamlStr);
            }
            if (yamlStr.Contains("port:"))
            {
                config.Port = GetValueOfPropertyYaml(yamlStr);
            }
            if (yamlStr.Contains("dbName:"))
            {
                config.DbName = GetValueOfPropertyYaml(yamlStr);
            }
            if (yamlStr.Contains("userName:"))
            {
                config.UserName = GetValueOfPropertyYaml(yamlStr);
            }
            if (yamlStr.Contains("password:"))
            {
                config.Password = GetValueOfPropertyYaml(yamlStr);
            }
        }
        ;
        // use filled `config` variable below.

您的模特:

public class Database
{
    public string Host { get; set; }
    public string Port { get; set; }
    public string DbName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
}

注意:我强烈建议您使用库,因为它已经过测试并且运行良好(我的方法应该经过正确测试)