日期:2014-05-18  浏览次数:20862 次

C#对含有非标准字段的ini文件的读写问题
根据网上的教程添加了一个类来实现ini文件的读写:
C# code
public class IniFile
        {
            public string Path;

            [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 inipath)
            {
                Path = inipath;
            }
            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();
            }
            public bool ExistINIFile()
            {
                return File.Exists(this.Path);
            }
        }


然后用file.IniReadValue("字段名", "键名")就能读取响应键的值,很方便,但问题是现在要处理的ini文档含有非标准的字段,如下所示:

[Section]
app1.exe
app2.exe
app3.exe

也就是字段名下没有键名,直接就是所需要读取的值,并且每行一个,对于这个字段下的数据我该怎么读取出来并且添加到一个ListBox呢?
我刚开始学C#,菜的很,希望各位大虾指点啊!!

------解决方案--------------------
这不能用INI API函数了吧!

手写的,不排除有拼写错误:
C# code
 
StreamReader sr = null;
try
{
                bool section = false;
                sr = new StreamReader(@"..\yourFile.ini", System.Text.Encoding.Default);
                while (sr.Peek() > -1)//从文件中读取行,一直读到文件尾
                  {
                   string rl = sr.ReadLine();
                   if(rl == "[Section]")section = true;
                   if(!section) continue;

                   if(rl.IndexOf('[')== 0) break;

                   listbox1.Items.Add(rl);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if(sr != null) sr.Close();
            }

------解决方案--------------------
如果符合ini文件格式,
Read/Write XML files, Config files, INI files, or the Registry
By Alvaro Mendez
http://www.codeproject.com/KB/cs/readwritexmlini.aspx