Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have xx.txt file with few sections and each section consists of some keys and values.

I want remove all keys and values under a specified section. After removing the data (keys and values) I have to add new keys and values under the "specified section".

before removing keys and values under section1
[Section1]
ask=ok
int=123

After:
[Section1]
string=xxxx
char=cccc

Please help me on this.

Thanks in advance...
Posted
Comments
CHill60 4-Jul-14 8:56am    
What have you tried?
Richard Deeming 4-Jul-14 9:03am    
This might help:
http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c
Sergey Alexandrovich Kryukov 4-Jul-14 11:39am    
Is it some kind of implementation of INI file? Then it depends on how you designed the code in general. The question makes no to little sense. It's just some work to do, pretty simple.

More importantly, INI files are usually not designed to be modified. Chances are, you need to use some other technology.

—SA

You can try to do it this way

Use the native methods for reading and writing a whole section.
C#
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);

[DllImport("kernel32.dll")]
static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);


This is how you read the data:
C#
uint MAX_BUFFER = 32767;
IntPtr pReturned = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSection("section1", 
                       pReturnedString, MAX_BUFFER, "test.ini");

string returned = Marshal.PtrToStringAuto(pReturned, 
                     (int)(bytesReturned - 1));
string[] section = returned.Split('\0');
// Do what you like with these values


And this is how you write the data:
C#
StringBuilder sbOutput = new StringBuilder();
sbOutput.Append("string=xxxx");
sbOutput.Append('\0');
sbOutput.Append("char=cccc");
WritePrivateProfileSection("section1", sbOutput.ToString(), "test.ini");

The section is now updated with the new keys.


Then if you should do this is another question all together.
 
Share this answer
 
v3
If you move over to storing configuration details as xml, you can use the ConfigurationManager[^] class to parse configuration sections in a file.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900