如何在C#中读写ini文件 [英] How to read and write ini file in C#

查看:82
本文介绍了如何在C#中读写ini文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读该部分并键入它的时候只有部分名称

我的文件是这样的。



[DefaultNames]

default1

default2



[DefaultType]

default1 = 1;

default2 = 2;

请帮我看看如何阅读并将DefaultNames分配到组合框中?



我有什么试过:



while reading the section and key it's coming only section name
my file is like this.

[DefaultNames]
default1
default2

[DefaultType]
default1=1;
default2=2;
Please help me how to read and assign DefaultNames into combobox?

What I have tried:

public class IniFile
   {
      public string path;
     // string Path = System.Environment.CurrentDirectory+"\\"+"ConfigFile.ini";
         
       [DllImport("kernel32")]
       private static extern long WritePrivateProfileString(string section,
           string key, string val, string filePath);
       [DllImport("kernel32")]
       private static extern int GetPrivateProfileString(string section,
                string key, string def, StringBuilder retVal,
           int size, string filePath);
      public IniFile(string Path)
       {
           path = Path;
       }
       
       public void IniWriteValue(string Section, string Key, string Value)
       {
           WritePrivateProfileString(Section, Key, Value, this.path);
       }
      
       public string IniReadValue(string Section, string Key)
       {
           StringBuilder temp = new StringBuilder(255);
           int i = GetPrivateProfileString(Section, Key, "", temp,
                                           255, this.path);
           return temp.ToString();

       }
    }

//In mail Class
   public string ReadConfig(string section, string key)
        {
            string retVal = string.Empty;
            string bankname = string.Empty;
            string basePath = System.Environment.CurrentDirectory + "\\" + "Settings";
            IniFile ini = new IniFile(basePath + "\\" + "ConfigFile.ini");
            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);
                ini.IniWriteValue("DefaultNames", "default1", "2");
                ini.IniWriteValue("DefaultNames", "default2", "1");
                
            }
            retVal = ini.IniReadValue(section, key);
            return retVal;
        } 

推荐答案

首先要做的事情是:不要在应用程序目录中存储配置文件(或任何其他数据) - 虽然它在开发中工作,但它在发布时往往会失败,因为Program Files文件夹及其子文件夹几乎都是为了病毒安全而写保护。

见这里:我应该在哪里存储我的数据? [ ^ ] - 它显示了一些更好的地方,并解释了如何访问它们。

其次,INI文件是一种非常古老的格式 - 有更现代的方法可以做到这一点。请参阅在C#中使用设置 [ ^ ]

第三,不要使用字符串连接来构建文件路径 - 而是使用Path.Combine。

First things first: don't store config files (or any other data) in your application directory - while it works in development, it tends to fail in release, because the "Program Files" folder and it's subfolders are pretty much write protected for virus security.
See here: Where should I store my data?[^] - it shows some better places, and explains how to access them.
Secondly, INI files are a very old format - there are more modern ways to do this. See Using Settings in C#[^]
Thirdly, don't use string concatenation to build a file path - use Path.Combine instead.
IniFile ini = new IniFile(Path.Combine(basePath, "ConfigFile.ini"));

它确保斜杠是正确的以及需要它们的位置。



最后......我尝试了你的代码:它有效。

It makes sure slashes are correct and where they are needed.

And finally...I tried your code: it worked.

string s = ReadConfig("DefaultType", "default1");

退回1





我只想阅读.ini文件和所有多个密钥我想给它选择组合框。



啊。你没有写代码,你不知道它是如何工作的,你根本无法理解......:叹息:

当你在互联网上找到随机代码时,它不能完全适合你想做的事情 - 你将永远不得不改变它,或者使用它有点不同。

在这种情况下,你想要使用不同的方法:

Returned "1"


"I just want to read .ini file and all multiple keys want to assign combobox that it ."

Ah. You didn't write the code, you don't know how it works, and you can't understand it at all...:sigh:
When you find random code on the internet, it isn't going to fit exactly what you want to do - you will always have to change it, or use it a little differently.
In this case, you want to use a different method:

myComboBox.DataSource = ReadConfigSection(Path.Combine(basePath, "ConfigFile.ini"), "DefaultType");



这很简单:


And that is pretty easy:

[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpszReturnBuffer, int nSize, string lpFileName);
public List<string> ReadConfigSection(string iniFilePath, string sectionName)
    {
    List<string> result = new List<string>();
    byte[] buffer = new byte[4096];
    GetPrivateProfileSection(sectionName, buffer, 4096, iniFilePath);
    String[] tmp = Encoding.ASCII.GetString(buffer).Trim('\0').Split('\0');
    foreach (String entry in tmp)
        {
        string[] parts = entry.Split('=');
        if (parts.Length == 2)
            {
            result.Add(parts[0]);
            }
        }
    return result;
    }

但是......在新项目中使用INI文件真的不是一个好主意。有更多的最新方法。

But...using INI files in a new project is really not a good idea. There are much more up-to-date ways to do that.


这篇关于如何在C#中读写ini文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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