利用系统API函数 GetPrivateProfileString 可以方便地读取ini文件。使用方法如下
(1)MyApp.INI文件的内容为
VB程序读取这个ini文件,将窗口的标题换为银哪Title指定的字符串
(2)新建一个VB工程
(3)Form1窗体代码
Option ExplicitPrivate Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringW" _
(ByVal lpApplicationName As Long, _
ByVal lpKeyName As Long, _
ByVal lpDefault As Long, _
ByVal lpReturnedString As Long, _
ByVal nSize As Long, _
ByVal lpFileName As Long) As Long
模厅
'------------
'读INI文件
'------------
Private Function GetValueFromINIFile(ByVal SectionName As String, _
ByVal KeyName As String, _
ByVal IniFileName As String) As String
Dim strBuf As String
'128个字符,初始化时用 0 填充
strBuf = String(128, 0)
GetPrivateProfileString StrPtr(SectionName), _
StrPtr(KeyName), _
StrPtr(""), _
StrPtr(strBuf), _
128, _
StrPtr(IniFileName)
'去除多余的 0
strBuf = Replace(strBuf, Chr(0), "")
GetValueFromINIFile = strBuf
End Function
Private Sub Form_Load()
Dim title As String
'读取INI文件中指定的节和节/键
'节的名称:AppName
'键名称:Title
title = GetValueFromINIFile("AppName", "Title", "c:\MyApp.INI")
旦搏隐 Me.Caption = title
End Sub
(4)运行效果
窗口的标题被设置Ini文件指定的字符串!
using System.IO;判陆孙断文件是否存在
if (File.Exists(filePath))
读取文件到字符串指没内唯悉纳
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(stream, Encoding.Default))
{
String str = reader.ReadToEnd()
}
}
然后,把str显示到相应位置就好了。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)