咖啡心情

咖啡般的生活,咖啡般的心情

« 谁容易?搬家,搬家 »

VB.net读配置文件

工资计算软件批量计算版由于业务复杂,申请使用vb.net 开发了。再一次读INI,却发现需要在.Net中使用API了,既然是.Net 还是尽量使用Framework的托管代码代替API吧。既然没有INI读写功能,就弄一个模块出来,Google一下,嘿嘿,还真有好人啊,拿来改改:

'=================================================
'模块功能: 读取INI配置文件
'引用参数: iniKey(string) Key名
'返回结果: Key 对应的Value
'=================================================

Function GetIniInfo(ByVal iniKey As String) As String
Dim iniRead As New StreamReader("parameter.ini")
Dim iniStr As String = iniRead.ReadToEnd
Dim i,cLine As Integer
Dim noSec As Boolean = False
Dim getValue As String = ""
Dim cLst
cLst = iniStr.Split(Chr(13))
cLine = UBound(cLst)
For i = 0 To cLine
If cLst(i).indexof("=") > 0 Then
If cLst(i).split("=")(0).trim() = iniKey Then
noSec = True
getValue = cLst(i).split("=")(1).trim()
Return getValue
Exit For
End If
End If
Next
End Function

没有读取Section功能,整个配置文件一窝端了……
程序写出来了,读他30个试试,饿地神阿,这个慢啊……

再看API方法:
Private Declare Function GetPrivateProfileString()Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Int32, ByVal lpFileName As String) As Int32
Private Declare Function WritePrivateProfileString()Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, ByVal lpFileName As String) As Int32

'定义读取配置文件函数
Public Function GetINI()Function GetINI(ByVal Section As String, ByVal AppName As String, ByVal lpDefault As String, ByVal FileName As String) As String
Dim Str As String = LSet(Str, 256)
GetPrivateProfileString(Section, AppName, lpDefault, Str, Len(Str), FileName)
Return Microsoft.VisualBasic.Left(Str, InStr(Str, Chr(0)) - 1)
End Function

'定义写入配置文件函数
Public Function WriteINI()Function WriteINI(ByVal Section As String, ByVal AppName As String, ByVal lpDefault As String, ByVal FileName As String) As Long
WriteINI = WritePrivateProfileString(Section, AppName, lpDefault, FileName)
End Function
Private Sub Form1_Load()Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim path As String
path = Application.StartupPath + "\server.ini"
TextBox1.Text = GetINI("Server", "IP", "", path)
TextBox2.Text = GetINI("Server", "port", "", path)
End Sub
Private Sub Button1_Click()Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim path As String
path = Application.StartupPath + "\server.ini"
WriteINI("Server", "IP", TextBox1.Text, path)
WriteINI("Server", "port", TextBox2.Text, path)
MsgBox("配置设置已经成功!!!!")
Me.Close()
Catch ex As Exception
MsgBox("错误!!!!")
End Try
End Sub

都是能用的,自己看着办。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新评论及回复

最近发表

Powered By Z-Blog 1.8 Spirit Build 80722 Code detection by Codefense  theme by BokeZhuti

辽ICP备06011536号 Cafemood.net