如何从该部分删除键和值? [英] How to remove key and values from the section?

查看:93
本文介绍了如何从该部分删除键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有xx.txt文件,里面有几个部分,每个部分都包含一些键和值。



我想删除指定部分下的所有键和值。删除数据(键和值)后,我必须在指定部分下添加新的键和值。



删除第1部分下的键和值

[第1节]

ask = ok

int = 123



后:

[第1节]

string = xxxx

char = cccc



请帮帮我在这个。



提前谢谢......

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...

推荐答案

你可以试试这样做



使用原生方法读取和写入整个部分。

You can try to do it this way

Use the native methods for reading and writing a whole section.
[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:

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:

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.


如果您转到将配置详细信息存储为xml,则可以使用 ConfigurationManager [ ^ ]用于解析文件中配置节的类。
If you move over to storing configuration details as xml, you can use the ConfigurationManager[^] class to parse configuration sections in a file.


这篇关于如何从该部分删除键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆