65.9K
CodeProject 正在变化。 阅读更多。
Home

用于创建/读取/编辑 INI 文件的 .NET 类

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.26/5 (5投票s)

2007年1月15日

CPOL

1分钟阅读

viewsIcon

48785

在 VB.NET 中处理 INI 文件。

引言

我一直很难读取 INI 文件。我不想使用 API。所以我只是写了这些代码。

如何使用代码

创建了一个新类后,首先设置文件名。如果尚未创建 INI 文件,您可以添加标题文本以及任意数量的键和值。

Dim myIniFile As New IniFile
With myIniFile
    .Filename = "c:\MyIniFile.ini"  'or any other file
    If .OpenIniFile() Then
        Dim MyValue As String = .GetValue("MyKey")
        .SetValue("Last Use of Application", Date.Now.ToLongDateString)
        If Not .SaveIni Then
            MessageBox.Show("Trouble by writing Ini-File")
        End If
    Else
        MessageBox.Show("No Ini-File found")
    End If

类本身

想法是使用 DataTableDataSet。因此,不需要使用数组。这是代码:

Imports System.IO
Imports System.Math
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text

  Public Class IniFile

        Private _strFileName As String
        Private _strIniArgumentsBegins As String = "[Arguments]"
        Private _strPrefix As String
        Private _dt As DataTable
        Private _ds As DataSet
        Private _dv As DataView
        Private _dr As DataRow
        Private TmpStringInhaltKomplett As New StringBuilder
        Private StringIniFile As String


    
        Public Property Filename() As String
            Get
                Return _strFileName
            End Get
            Set(ByVal Value As String)
                _strFileName = Value
            End Set
        End Property
        Public Property Prefix() As String
            Get
                Return _strPrefix
            End Get
            Set(ByVal Value As String)
                _strPrefix = Value
            End Set
        End Property

现在,初始化组件

Public Sub New()
    _ds = New DataSet
    _dt = New DataTable
    _dv = New DataView

    _dt.Columns.Add("Key")
    _dt.Columns.Add("Value")

    _ds.Tables.Add(_dt)
    _dv.Table = _ds.Tables(0)
End Sub

OpenIniFile() 函数读取 INI 文件的每一行。在参数值 strIniArgumentsBegins 之后,键和值列表开始。每个新的键及其值都会添加到数据集。并且在一切完成后,更改将被接受

Public Function OpenIniFile() As Boolean
Try
    Dim tmpStringLine As String
    Dim tmpStringArguments() As String
    Dim tmpBool As Boolean = False
    If Not File.Exists(Filename) Then
        Return False
    End If
    Dim ssr As StreamReader = New StreamReader(Filename)
    _ds = New DataSet
    _dt = New DataTable
    _dv = New DataView
    _dt.Columns.Add("Key")
    _dt.Columns.Add("Value")

    _ds.Tables.Add(_dt)
    _dv.Table = _ds.Tables(0)
    Do
        tmpStringLine = ssr.ReadLine()
        If tmpStringLine Is Nothing Then Exit Do
        If tmpBool Then
            Try
                tmpStringArguments = tmpStringLine.Split("=")
                _dr = _ds.Tables(0).NewRow
                _dr("Key") = tmpStringArguments(0)
                _dr("Value") = tmpStringArguments(1)
                _ds.Tables(0).Rows.Add(_dr)
            Catch ex As Exception

            End Try
        End If
        If tmpStringLine.StartsWith(_strIniArgumentsBegins) Then
            tmpBool = True
            _strPrefix = TmpStringInhaltKomplett.ToString
        End If
        TmpStringInhaltKomplett.Append(tmpStringLine & Environment.NewLine)
        Loop Until tmpStringLine Is Nothing
        ssr.Close()
        StringIniFile = TmpStringInhaltKomplett.ToString
        Return True
        _ds.AcceptChanges()
    Catch ex As Exception
        Return False
    End Try
End Function

GetValue 中的值将从 DataView 中读取

Public Function GetValue(ByVal Key As String) As String
    _dv.RowFilter = "Key = '" & Key & "'"
    If _dv.Count > 0 Then
        Return _dv.Item(0).Item("Value")
    Else
        Return "NOTHING"
    End If
End Function

要在 SetValue 中设置值,DataView 会检查是否需要添加或更改键

Public Function SetValue(ByVal Key As String, ByVal Value As String) As Boolean
    _dv.RowFilter = "Key = '" & Key & "'"
    If _dv.Count > 0 Then
        _dv.Item(0).Item("Value") = Value
        Console.WriteLine("Änderung am Key '{0}'", Key)
    Else
        _dr = _ds.Tables(0).NewRow
        _dr("Key") = Key
        _dr("Value") = Value
        _ds.Tables(0).Rows.Add(_dr)
        Console.WriteLine("Neuer Eintrag: Key ='{0}' & Value = {1}", Key, Value)
    End If
End Function

最后一步,需要保存更改。在这里,将检查是否有任何更改以及文件是否已经存在

Public Function SaveIni() As Boolean
    If Not IsNothing(_ds.GetChanges) Then
        SetValue("_LastSaveOfIniFile", Date.Now.ToLongDateString)
        Try
            _dv.RowFilter = ""
            _dv.Sort = "KEY ASC"
            Dim StringIni As New StringBuilder
            StringIni.Append(_strPrefix & Environment.NewLine)
            StringIni.Append(_strIniArgumentsBegins & Environment.NewLine)
            Dim i As Integer
            For i = 0 To _dv.Count - 1
                StringIni.Append(_dv.Item(i).Item("Key") & "=" & _
                                 _dv.Item(i).Item("Value") & Environment.NewLine)
            Next
            If File.Exists(_strFileName) Then File.Delete(_strFileName)
            Dim ssw As New StreamWriter(_strFileName)
            ssw.WriteLine(StringIni.ToString)
            ssw.Close()
            _ds.AcceptChanges()
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return True
    End If
End Function

最后,类必须结束

End Class

评估

遵循“KISS”原则——保持简单和直观,一个新的类诞生了,可以帮助您舒适地编辑 INI 文件。

© . All rights reserved.