c#读取properties
时间: 2023-11-22 07:37:16 浏览: 141
在C#中,你可以使用`System.Configuration`命名空间下的`ConfigurationManager`类来读取properties文件。首先,确保你的项目引用了`System.Configuration`程序集。
假设你有一个名为`appSettings.properties`的properties文件,其中包含以下内容:
```
key1=value1
key2=value2
```
你可以使用以下代码读取该文件:
```csharp
using System;
using System.Configuration;
class Program
{
static void Main()
{
// 读取properties文件
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "appSettings.properties";
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
KeyValueConfigurationCollection appSettings = configuration.AppSettings.Settings;
// 获取属性值
string value1 = appSettings["key1"].Value;
string value2 = appSettings["key2"].Value;
// 输出属性值
Console.WriteLine($"key1: {value1}");
Console.WriteLine($"key2: {value2}");
}
}
```
运行上述代码,你将会得到以下输出:
```
key1: value1
key2: value2
```
这样,你就成功读取了properties文件中的键值对。请确保将`appSettings.properties`文件放在正确的目录下,并根据需要更改文件路径。
阅读全文
相关推荐
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)