HOW TO:配置或数据文件的保存

数据

  配置类或数据类都需要可序列化。通常,序列化有三种方式,序列化和反序列化的过程可以做成一个静态类,如下:

Public Class SerializeHelperClass SerializeHelper

    Private Sub New()Sub New()
    End Sub

    Private Shared Function GetXML()Function GetXML(ByVal obj As Object) As String
        Dim mSerializer As New System.Xml.Serialization.XmlSerializer(obj.GetType)
        Dim mStringWriter As New System.IO.StringWriter
        mSerializer.Serialize(mStringWriter, obj)
        Return mStringWriter.ToString
    End Function

    Private Shared Function GetObj()Function GetObj(ByVal objtype As Type, ByVal xml As String) As Object
        Dim mSerializer As New System.Xml.Serialization.XmlSerializer(objtype)
        Dim mStringReader As New System.IO.StringReader(xml)
        Return mSerializer.Deserialize(mStringReader)
    End Function

    Private Shared Sub SaveXmlFile()Sub SaveXmlFile(ByVal filename As String, ByVal obj As Object)
        Dim XmlWriter As New System.IO.StreamWriter(filename, False)
        XmlWriter.Write(GetXML(obj))
        XmlWriter.Close()
    End Sub

    Private Shared Function LoadXmlFile()Function LoadXmlFile(ByVal filename As String, ByVal objtype As Type) As Object
        Dim XmlReader As New System.IO.StreamReader(filename, System.Text.Encoding.Default)
        Dim mObj As Object
        mObj = GetObj(objtype, XmlReader.ReadToEnd)
        XmlReader.Close()
        Return mObj
    End Function

    Private Shared Sub SaveSerializerFile()Sub SaveSerializerFile(ByVal filename As String, ByVal formatter As System.Runtime.Serialization.IFormatter, ByVal obj As Object)
        Dim mFileStream As System.IO.Stream = System.IO.File.Open(filename, System.IO.FileMode.Create)
        formatter.Serialize(mFileStream, obj)
        mFileStream.Close()
    End Sub

    Private Shared Function LoadDeSerializeFile()Function LoadDeSerializeFile(ByVal FileName As String, ByVal formatter As System.Runtime.Serialization.IFormatter) As Object
        Dim mFileStream As System.IO.Stream = System.IO.File.Open(FileName, System.IO.FileMode.Open)
        Dim mObj As Object
        mObj = formatter.Deserialize(mFileStream)
        mFileStream.Close()
        Return mObj
    End Function

    Public Shared Function Clone()Function Clone(ByVal obj As Object) As Object
        Dim mFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim mMemoryStream As New System.IO.MemoryStream
        mFormatter.Serialize(mMemoryStream, obj)
        mMemoryStream.Position = 0
        Return mFormatter.Deserialize(mMemoryStream)
    End Function

    Public Shared Sub Save()Sub Save(ByVal filename As String, ByVal formattype As FormatType, ByVal obj As Object)
        Select Case formattype
            Case formattype.Binary
                SaveSerializerFile(filename, New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, obj)
            Case formattype.Soap
                SaveSerializerFile(filename, New System.Runtime.Serialization.Formatters.Soap.SoapFormatter, obj)
            Case formattype.Xml
                SaveXmlFile(filename, obj)
        End Select
    End Sub

    Public Shared Function Load()Function Load(ByVal filename As String, ByVal formattype As FormatType, ByVal XmlFormatObjType As Type) As Object
        Select Case formattype
            Case formattype.Binary
                Return LoadDeSerializeFile(filename, New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)
            Case formattype.Soap
                Return LoadDeSerializeFile(filename, New System.Runtime.Serialization.Formatters.Soap.SoapFormatter)
            Case formattype.Xml
                Return LoadXmlFile(filename, XmlFormatObjType)
        End Select
        Return Nothing
    End Function

    Public Enum FormatTypeEnum FormatType
        Xml
        Binary
        Soap
    End Enum
End Class

  类的一个实例就是一项数据,如果有多个配置可选或者有多项数据,那就是一个数据集合了。在保存配置时,其实是将数据集合保存到文件里去。所以这里用集合的概念来处理。
为了使处理简单些,我引进一个接口,要求每个配置类或数据类必需实现这个接口。

Public Interface IConfigInformationInterface IConfigInformation
    Property Name()Property Name() As String
End Interface

  NAME其实是字典键值。

  处理的基类:

Public MustInherit Class ConfigInformationCollectionBaseClass ConfigInformationCollectionBase(Of TConfigInformation As IConfigInformation)
    Inherits System.Collections.DictionaryBase

    Private gformattype As SerializeHelper.FormatType = SerializeHelper.FormatType.Binary
    Private gFileName As String = AppDomain.CurrentDomain.BaseDirectory & "{0}.dat" '{0}默认取类名,{1},文件后缀,这里默认都取为dat

    Public Sub Add()Sub Add(ByVal item As TConfigInformation)
        If Not Me.Dictionary.Contains(item.Name) Then Me.Dictionary.Add(item.Name, item)
    End Sub

    Public Sub Remove()Sub Remove(ByVal Name As String)
        If Me.Dictionary.Contains(Name) Then Me.Dictionary.Remove(Name)
    End Sub

    Public ReadOnly Property Items()Property Items() As TConfigInformation()
        Get
            Dim tmp(Me.Count - 1) As TConfigInformation
            Me.Dictionary.Values.CopyTo(tmp, 0)
            Return tmp
        End Get
    End Property

    Public ReadOnly Property Names()Property Names() As String()
        Get
            Dim tmp(Me.Count - 1) As String
            Me.Dictionary.Keys.CopyTo(tmp, 0)
            Return tmp
        End Get
    End Property

    Public Overloads Sub Clear()Sub Clear()
        Me.Dictionary.Clear()
    End Sub

    Default Public ReadOnly Property Item()Property Item(ByVal Name As String) As TConfigInformation
        Get
            Return CType(Me.Dictionary.Item(Name), TConfigInformation)
        End Get
    End Property

    Public Sub Save()Sub Save()
        Dim mItems(Me.Count - 1) As TConfigInformation
        Me.InnerHashtable.Values.CopyTo(mItems, 0)
        SerializeHelper.Save(gFileName, gformattype, mItems)
    End Sub

    Private Sub Load()Sub Load()
        If Not IO.File.Exists(gFileName) Then
            Initialize()
            Save()
        Else
            Dim mItems() As TConfigInformation
            mItems = CType(SerializeHelper.Load(gFileName, gformattype, GetType(TConfigInformation)), TConfigInformation())
            For Each item As TConfigInformation In mItems
                Me.Add(item)
            Next
        End If
    End Sub

    '继承时,若有初始赋值,在此实现
    Public MustOverride Sub Initialize()Sub Initialize()

    '默认为FormatType.Binary
    Sub New()Sub New()
        gFileName = String.Format(gFileName, GetType(TConfigInformation).Name)
        Me.Load()
    End Sub

    Sub New()Sub New(ByVal formattype As SerializeHelper.FormatType)
        gFileName = String.Format(gFileName, GetType(TConfigInformation).Name)
        gformattype = formattype
        Me.Load()
    End Sub

    Sub New()Sub New(ByVal file As String, ByVal formattype As SerializeHelper.FormatType)
        gFileName = file
        gformattype = formattype
        Me.Load()
    End Sub

End Class

  使用举例:

  1、定义配置或数据类

<Serializable()> _
Public Class MyConfigInfoClass MyConfigInfo
    Implements IConfigInformation

    Private mMachine As String
    Private mLogins(-1) As Login

    Public Property Machine()Property Machine() As String Implements IConfigInformation.Name
        Get
            Return mMachine
        End Get
        Set(ByVal value As String)
            mMachine = value
        End Set
    End Property

    Public ReadOnly Property Logins()Property Logins() As Login()
        Get
            Return mLogins
        End Get
    End Property

    Public Sub Add()Sub Add(ByVal login As Login)
        ReDim Preserve mLogins(mLogins.Length)
        mLogins(mLogins.Length - 1) = login
    End Sub

    <Serializable()> _
    Public Class LoginClass Login
        Private mUser As String
        Private mPass As String

        Public Property User()Property User() As String
            Get
                Return mUser
            End Get
            Set(ByVal value As String)
                mUser = value
            End Set
        End Property

        Public Property Pass()Property Pass() As String
            Get
                Return mPass
            End Get
            Set(ByVal value As String)
                mPass = value
            End Set
        End Property

        Sub New()Sub New()
        End Sub

        Sub New()Sub New(ByVal user As String, ByVal pass As String)
            Me.User = user
            Me.Pass = pass
        End Sub
    End Class
End Class

  2、实现处理

Public Class ConfigDataClass ConfigData
    Inherits ConfigInformationCollectionBase(Of MyConfigInfo)

    Sub New()Sub New()
        MyBase.New()
    End Sub
    Sub New()Sub New(ByVal formattype As SerializeHelper.FormatType)
        MyBase.New(formattype)
    End Sub

    Sub New()Sub New(ByVal file As String, ByVal formattype As SerializeHelper.FormatType)
        MyBase.New(file, formattype)
    End Sub

    '这是默认值,如果没有数据文件则生成文件并同时添加这些数据;若已存在文件,这里略去,不会处理。
    Public Overrides Sub Initialize()Sub Initialize()
        Dim item As MyConfigInfo

        item = New MyConfigInfo
        With item
            .Machine = "Fk-A01-02"
            .Add(New MyConfigInfo.Login("LzmTW", "001"))
            .Add(New MyConfigInfo.Login("Lzm", "002"))
        End With
        Me.Add(item)

        item = New MyConfigInfo
        With item
            .Machine = "Fk-A01-03"
            .Add(New MyConfigInfo.Login("L", "003"))
            .Add(New MyConfigInfo.Login("Lz", "004"))
            .Add(New MyConfigInfo.Login("LzmTW", "001"))
        End With
        Me.Add(item)
    End Sub
End Class

  测试:

    Private Sub Button3_Click()Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim test As New ConfigData
        Console.WriteLine(test.Item("Fk-A01-03").Logins(0).User) 'L
        test.Item("Fk-A01-03").Logins(0).User = "Hello"
        test.Save() '存盘
        '用另一个打开,看看
        Dim test2 As New ConfigData
        Console.WriteLine(test2.Item("Fk-A01-03").Logins(0).User) 'Hello
    End Sub

时间: 2024-12-09 18:28:46

HOW TO:配置或数据文件的保存的相关文章

HOW TO:配置或数据文件的保存(改进)

数据 HOW TO:配置或数据文件的保存 这个原是基于NET2003,其中又用了2005的泛型(OF TConfigInformation),显得不伦不类.现在改为2005的,并取消了接口的引入. 序列化类: Public Class SerializeHelperClass SerializeHelper(Of T)     Private Sub New()Sub New()    End Sub     <System.ComponentModel.EditorBrowsable(Comp

c++读取txt文件里的数据,然后保存在二维数组中进行处理

问题描述 c++读取txt文件里的数据,然后保存在二维数组中进行处理 我写的程序是把数据自己输入在主函数里,但是如果想实际的应用应该是有一个数据文件,然后提取出数据文件的数据保存在二维数组中才对,而且这个二维数组要根据具体文件的大小定数组的行列数,有谁能帮我做一下吗,谢谢! #include #include #include using namespace std; #define M 10//二维数组的行 #define N 6//二维数组的列 class Data { double a[M

linux oracle rac expdp导出数据库,在节点1执行导出但是数据文件保存在了节点2上

问题描述 linux oracle rac expdp导出数据库,在节点1执行导出但是数据文件保存在了节点2上 linux oracle rac expdp导出数据库,在节点1(机器1)执行导出,数据文件保存在了节点2(机器2)上,怎么指定导出到哪个节点(哪台机器)的目录下?或者让两个节点的目录下都有导出的数据文件.

ZooKeeper#1:数据文件

在ZK里面有两个数据文件目录可以配置, dataDir, The location where ZooKeeper will store the in-memory database snapshots. dataLogDir, This option will direct the machine to write the transaction log to the dataLogDir rather than the dataDir. dataDir用来存储ZKDatabase的快照文件(

XML基础之 DataSet加载XML数据文件

xml|加载|数据 在开发系统时,经常会有通过Code获取其Description,例如由错误号码获取错误信息. 这些错误信息可以存放到XML数据文件中,通过DataSet对象进行读取. 下面是读取的函数:   public string GetError(int ErrorId)  {   //在进行错误显示时,可以将错误号对应的文本描述放到一个XML   //文件中.这是支持多语言的一种通用方法.   //本示例从一个xml文件中取出数据,并获取指定ID号的错误描述.    string f

没有备份、只有归档日志,如何恢复数据文件?

备份|恢复|数据 没有备份.只有归档日志,如何恢复数据文件?系统环境: 1.操作系统:Windows 2000 Server,机器内存128M2.数据库: Oracle 8i R2 (8.1.6) for NT 企业版3.安装路径:C:\ORACLE模拟现象: 可通过重建数据文件来恢复,前提是归档日志文件保存完整先将数据库设置为归档模式SQL*Plusconn system/manager--创建实验表空间create tablespace test datafile'c:\test.ora'

通过实例学习ASP读取XML数据文件的方法

xml|数据 通过实例学习ASP读取XML数据文件的方法,希望大家能很快掌握,提供两段代码. 分别保存下面两段代码,一个保存为readxml.asp另一个保存为test.xml,放在同一个目录下面,调试程序即可,在程序里面我已经做了解释,读取代码可以做成一个readxml的函数,通过使用输入的参数而读取xml不同数据记录的不同的值.这段程序的改编来自互联网,有什么出入请见谅. readxml.asp <%dim xml,objNode,objAtr,nCntChd,nCntAtrSet xml=

tempdb数据文件突然增大的原因

上周公司的生产库的tempdb瞬间暴涨,导致磁盘剩余空间为0,估计是相关人员运行不合理的sql查询导致. tempdb在以下情况会用到: (1)用户建立的临时表.如果能够避免不用,就尽量避免. 如果使用临时表储存大量的数据且频繁访问,考虑添加index以增加查询效率. (2)Schedule jobs.如DBCC CHECKDB会占用系统较多的资源,较多的使用tempdb.最好在SQL Server loading比较轻的时候做. (3)Cursors.游标会严重影响性能应当尽量避免使用. (4

Oracle中通过DATA GUARD手工管理数据文件

一般情况下,会采用自动管理standby数据库文件文件的方式,但是有时候会采用手工方式管理,比如standby数据库使用裸设备的情况. 看一个例子: SQL> select name, open_mode, database_role, db_unique_name 2  from v$database; NAME                           OPEN_MODE  DATABASE_ROLE    DB_UNIQUE_NAME ----------------------