I'm looping through a txt file currently to get server names and check a specific services status and start it if stopped. This works perfectly with my service names stored in my app.config. What I want to do is also store my file path, file name, timeout, and any other keys I want to put in the app.config down the road. My issue is when I loop through the app.config currently I only have service names which works perfectly. If I add the other keys that I want to add I obviously will get "Service Not Found". How do I only pick keys that ar开发者_如何学编程e "like" "service". I'm naming the keys "service1", 2, 3, etc.
foreach (string key in ConfigurationManager.AppSettings)
{
string value = ConfigurationManager.AppSettings[key];
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(txtFilePath + txtFile))
{
String line;
// Read and display lines from the file until the end
// of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
// Check for lines with semi-colon. If semi-colon at
// line start skip it
if (line.StartsWith(";"))
{
continue;
}
else
{
ServiceController sc = new ServiceController(value, line);
//Create new timeout module.
TimeSpan timeout = new TimeSpan();
//Write current service status to console.
Console.WriteLine(
"The " + value + " service status is currently set to {0}",
sc.Status.ToString()
);
You should move to a named configuration section with elements that you define VS using the AppSetting collection.
I'd follow the recommendations here on how to make a custom section in your config file, and then you're no longer finding items by key, but by section.
精彩评论