我在这里搜索,没有找到解决我问题的答案,我有一个程序,可以读取报告(txt文件),并自动填充工作簿中工作表的特定单元格。我已经创建了一个ini文件,用户将根据需要进行更新。
public class IniFile
{
[DllImport("kernel32")]
static extern int GetPrivateProfileString(string Section, string Key,
string Value, StringBuilder Result, int Size, string FileName);
[DllImport("kernel32")]
static extern int GetPrivateProfileString(string Section, int Key,
string Value, [MarshalAs(UnmanagedType.LPArray)] byte[] Result,
int Size, string FileName);
[DllImport("kernel32")]
static extern int GetPrivateProfileString(int Section, string Key,
string Value, [MarshalAs(UnmanagedType.LPArray)] byte[] Result,
int Size, string FileName);
public string path;
public IniFile(string INIPath)
{
path = INIPath;
}
public string[] GetSectionNames()
{
for (int maxsize = 500; true; maxsize *= 2)
{
byte[] bytes = new byte[maxsize];
int size = GetPrivateProfileString(0, "", "", bytes, maxsize, path);
if (size < maxsize - 2)
{
string Selected = Encoding.ASCII.GetString(bytes, 0,
size - (size > 0 ? 1 : 0));
return Selected.Split(new char[] { '\0' });
}
}
}
public string[] GetEntryKeyNames(string section)
{
for (int maxsize = 500; true; maxsize *= 2)
{
byte[] bytes = new byte[maxsize];
int size = GetPrivateProfileString(section, 0, "", bytes, maxsize, path);
if (size < maxsize - 2)
{
string entries = Encoding.ASCII.GetString(bytes, 0,
size - (size > 0 ? 1 : 0));
return entries.Split(new char[] { '\0' });
}
}
}
public object GetEntryKeyValue(string section, string entry)
{
for (int maxsize = 250; true; maxsize *= 2)
{
StringBuilder result = new StringBuilder(maxsize);
int size = GetPrivateProfileString(section, entry, "",
result, maxsize, path);
if (size < maxsize - 1)
{
return result.ToString();
}
}
}
}
}
以下是我正在使用的代码:
List<string> PlacesList= new List<string>();
List<string> PositionsList= new List<string>();
private void btnReadini_Click(object sender, EventArgs e)
{
IniFile INI = new IniFile(@"C:\Races.ini");
try
{
string[] SectionHeader = INI.GetSectionNames();
if (SectionHeader != null)
{
foreach (string SecHead in SectionHeader)
{
listBox1.Items.Add("");
listBox1.Items.Add("[" +SecHead+"]");
string[] Entry = INI.GetEntryKeyNames(SecHead);
if (Entry != null)
{
foreach (string EntName in Entry)
{
listBox1.Items.Add( EntName +"=" +
INI.GetEntryKeyValue(SecHead, EntName));
}
}
}
}
}
catch (Exception ex)
{
listBox1.Items.Add("Error: " + ex);
}
}
[Places]
IOM=Isle of man
UK=United Kingdom
IRE=Ireland
[Races]
IOM=7
UK=6
[Positions]
WN=Win
2nd=Second
3rd=Third
4th=Fourth
我现在可以读取ini文件并将其显示在我的列表框中,我现在想做的是将节[位置]的名称和值保存到一个名为PlacesList的列表中,并将位置的名称和值保存到一个名为PositionsList的列表中。使用当前的类,我可以读取所有部分、键和值,但如何仅将所需的数据放入列表?