Loading settings.
★★☆Many applications read and write settings into an initialisation (ini) file. Typically the data in the file is structured into blocks identified with square brackets. Each setting has a name, followed by an equal sign, followed by the data. E.g. in the example below, port is a setting and the data is 143.
[modified by]
name=Dave Hillyard
[database]
; use IP address in case network name resolution is not working
server=192.0.2.62
port=143
Write a program that reads the contents of a text file as shown above and outputs the data contained within it in the format:
Last modified by: Dave Hillyard
IP address: 192.0.2.62
Port number: 143
Remember to add a comment before a subprogram, selection or iteration statement to explain its purpose.
input_settings that:settings.ini. If the file is not found the message, "settings.ini file not found." is output and no further processing takes place.Note the data attributes can be anywhere in the file, not necessarily in the order presented above.
input_settings function is called.File contents for settings.ini:
[modified by]
name=Dave Hillyard
[database]
; use IP address in case network name resolution is not working
server=192.0.2.62
port=143
Output:
Last modified by: Dave Hillyard
IP address: 192.0.2.62
Port number: 143
// ini file program
using System;
using System.IO;
class Submission
{
---
// -------------------------
// Subprograms
// -------------------------
---
static void input_settings()
{
---
string file_name = "settings.ini";
string modified = "";
string ip = "";
string port = "";
---
// check file exists
try
{
---
StreamReader file = new StreamReader(file_name);
---
// Process each line in the file
string line;
while ((line = file.ReadLine()) != null)
{
---
line = line.Trim();
// Split data into a list, separated by an equal sign
string[] data = line.Split('=');
---
// If there are two items in the list, match the first item
if (data.Length > 1)
{
---
// Set the variable to be the second item
switch (data[0].Trim())
{
---
case "name":
modified = data[1].Trim();
break;
case "server":
ip = data[1].Trim();
break;
case "port":
port = data[1].Trim();
break;
---
}
---
}
---
}
---
file.Close();
Console.WriteLine($"Last modified by: {modified}");
Console.WriteLine($"IP address: {ip}");
Console.WriteLine($"Port number: {port}");
---
}
---
catch (FileNotFoundException)
{
---
Console.WriteLine("settings.ini file not found.");
---
}
---
}
---
// -------------------------
// Main program
// -------------------------
public static void Main(string[] args)
{
---
input_settings();
---
}
---
}