1
Answer

Use COM Interop to Read and Write INI files in C#

Photo of Administrator

Administrator

22y
634
1
Hello there, In the first place, thanx to federico and admin for helping me out with my previous problem on connection to SQL Server using Win authentication. But now i have another problem. I wanted to build a C# program that will have access to a SQL Server 2000 database. This sounds easy since you only need to build the connection string and the sql command and then hook it to the database. But what I want is a bit complicated as I wanted the values of the database connection string to be read from an INI file using Win32API. I found an article which is quite useful from the internet which teach us how to read from an INI file. The URL is : http://archive.devx.com/dotnet/discussions/040902/cominterop.asp But I wanted something more than what the web page can offer. I would like my program to be able to get some values from a key in a section and then process the values so that i can add it into a ComboBox. Example such as : [REPORT] REPORTNAMES=[productlocation],[inventory],[productmaster] In the above INI file, I wanted to separate the values within each of the [ ] i get from REPORTNAMES key in the REPORT section so that each one of them can be added to the ComboBox. Please help me out with this .... thanx =CmLaM=

Answers (1)

1
Photo of Administrator
Tech Writer 2.2k 1.6m 22y
It seems the way to go is to write your own parser. In C# this is a fairly easy task using the string and regular expression classes. Here are the rough steps: 1. Add using System.IO to your using section 2. Create a FileStream and a StreamReader using the Filestream 3. Loop through each line in the ini file and use the stream reader to read it as a string 4. Check if its a section with brackets, if so track it 5. Parse the pairs on either side of the equal sign under the section 6. if the value contains the regular expression matching a bracketed set [],[],[] then parse each value and place in an array (or add directly to your combobox. (You can also use the Split string command here with , as a delimiter) I would also consider using regular expressions to check if a line contains a section or a name/value pair. Then go to the appopriate method to handle parsing for this line. You can use the Regex class for this. -Mike