Jump to content

Recommended Posts

Posted

Boas novamente,

o que eu quero fazer é do genero ter um ficheiro .ini em que vai ficar o nome da base de dados e o caminho da mesma, e o programa ao arrancar ia ler e abrir esse mesmo, alg csg dar uma dica sobre esta situaçao?

o conteudo do ini:

[baseDados]

NomeBaseDados=XPTO

CaminhoBaseDados=C:\Programas\XPTO

cumprimentos

Posted

Porque não usam as builtin settings com âmbito à aplicação?

Cria um XML todo bonito com todas as settings que precisas.

Sérgio Ribeiro


"Great coders aren't born. They're compiled and released"
"Expert coders do not need a keyboard. They just throw magnets at the RAM chips"

Posted

Estou a escrever um exemplo em cima do joelho, Tive a almoçar entretanto mas já posto.

Quer um INI, damos um INI! Não quero que falte nada 😁

  • Vote 1

Sérgio Ribeiro


"Great coders aren't born. They're compiled and released"
"Expert coders do not need a keyboard. They just throw magnets at the RAM chips"

Posted

Aqui está, um pouco em cima do joelho mas até ficou porreirita para enfiar para uma classe e fazer uma coisa bonita... B)

Para testares, abre um projecto novo, mete 2 botões no form e substituí todo (mesmo todo) o código por este:

Public Class Form1

    Private INI As New Dictionary(Of String, Dictionary(Of String, String))
    Private UltimaChave As String = String.Empty
    Private UltimasEntradas As New Dictionary(Of String, String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim ofd As New OpenFileDialog
        ofd.Filter = "Ficheiros INI|*.ini"
        ofd.ShowDialog()

        Dim SR As New IO.StreamReader(ofd.FileName)
        While Not SR.EndOfStream
            ParseINI(SR.ReadLine)
        End While
        ParseINI("")
        SR.Close()
    End Sub

    Private Sub ParseINI(ByVal Linha As String)
        Select Case Strings.Left(Linha, 1)

            Case "["
                UltimaChave = Strings.Mid(Linha, 2, Linha.Length - 2)
            Case ""

                Dim TempUE As New Dictionary(Of String, String)
                For Each KVP As KeyValuePair(Of String, String) In UltimasEntradas
                    TempUE.Add(KVP.Key, KVP.Value)
                Next
                INI.Add(LCase(UltimaChave), TempUE)
                UltimaChave = String.Empty
                UltimasEntradas.Clear()

            Case Else
                If UltimaChave <> Nothing Then
                    Dim P() As String = Split(Linha, "=")
                    UltimasEntradas.Add(LCase(P(0)), P(1))
                End If

        End Select
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            'as duas que precisas
            MsgBox(INI("basedados")("nomebasedados"))
            MsgBox(INI("basedados")("caminhobasedados"))

            'e outra para veres
            MsgBox(INI("outracoisaqualquer")("outraquetanto"))
        Catch
            MsgBox("Chave inexistente")
        End Try
    End Sub
End Class

Acabei agora mesmo de a escrever, mas testei um INI com este conteúdo:

[baseDados]
NomeBaseDados=glamorama
CaminhoBaseDados=C:\Programas\XPTO

[OutraCoisaQualquer]
UmaSettingMarada=xpto
OutraQueTanto=Oh meu deus!!
EmaisOutraParaAsRestantesNaoFicaremSozinhas=lol, lol

Tou cá, aliás, estamos cá todos para esclarecimentos, se necessário.

EDIT: Esqueci-me de dizer que o button1 serve para carregar o INI e o button2 para ir consultar uns valores

Sérgio Ribeiro


"Great coders aren't born. They're compiled and released"
"Expert coders do not need a keyboard. They just throw magnets at the RAM chips"

Posted

Aqui está, um pouco em cima do joelho mas até ficou porreirita para enfiar para uma classe e fazer uma coisa bonita... B)

Para testares, abre um projecto novo, mete 2 botões no form e substituí todo (mesmo todo) o código por este:

Public Class Form1

    Private INI As New Dictionary(Of String, Dictionary(Of String, String))
    Private UltimaChave As String = String.Empty
    Private UltimasEntradas As New Dictionary(Of String, String)

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        Dim ofd As New OpenFileDialog
        ofd.Filter = "Ficheiros INI|*.ini"
        ofd.ShowDialog()

        Dim SR As New IO.StreamReader(ofd.FileName)
        While Not SR.EndOfStream
            ParseINI(SR.ReadLine)
        End While
        ParseINI("")
        SR.Close()
    End Sub

    Private Sub ParseINI(ByVal Linha As String)
        Select Case Strings.Left(Linha, 1)

            Case "["
                UltimaChave = Strings.Mid(Linha, 2, Linha.Length - 2)
            Case ""

                Dim TempUE As New Dictionary(Of String, String)
                For Each KVP As KeyValuePair(Of String, String) In UltimasEntradas
                    TempUE.Add(KVP.Key, KVP.Value)
                Next
                INI.Add(LCase(UltimaChave), TempUE)
                UltimaChave = String.Empty
                UltimasEntradas.Clear()

            Case Else
                If UltimaChave <> Nothing Then
                    Dim P() As String = Split(Linha, "=")
                    UltimasEntradas.Add(LCase(P(0)), P(1))
                End If

        End Select
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            'as duas que precisas
            MsgBox(INI("basedados")("nomebasedados"))
            MsgBox(INI("basedados")("caminhobasedados"))

            'e outra para veres
            MsgBox(INI("outracoisaqualquer")("outraquetanto"))
        Catch
            MsgBox("Chave inexistente")
        End Try
    End Sub
End Class

Acabei agora mesmo de a escrever, mas testei um INI com este conteúdo:

[baseDados]
NomeBaseDados=glamorama
CaminhoBaseDados=C:\Programas\XPTO

[OutraCoisaQualquer]
UmaSettingMarada=xpto
OutraQueTanto=Oh meu deus!!
EmaisOutraParaAsRestantesNaoFicaremSozinhas=lol, lol

Tou cá, aliás, estamos cá todos para esclarecimentos, se necessário.

quando abres o openfiledialog e depois metes cancelar dá erro xD

mas de resto está muito bom 🙂

Posted

LOL.

Está bem, acrescenta-lhe depois do ShowDialog:

If ofd.Filename=Nothing then Exit Sub

É um exemplo de como ele pode fazer, não está errorhandled. Só meti o TryCatch no fim porque ele podia exprimentar com o INI dele e a ultima chave não existe.

Sérgio Ribeiro


"Great coders aren't born. They're compiled and released"
"Expert coders do not need a keyboard. They just throw magnets at the RAM chips"

Posted

Tens este exemplo que é o que uso para ler os ficheiros INI.

Já não me lembro onde arranjei este código  B)

É simples de usar

    Private Declare Ansi Function GetPrivateProfileString Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
           (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, _
            ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer

    Public Function GetIniSetting(ByVal strKey As String, ByVal strSection As String, ByVal strIniFile As String) As String

        Dim strValue As String
        Dim intPos As Integer

        On Error GoTo ErrTrap

        strValue = Space(1024)

        GetPrivateProfileString(strSection, strKey, "INI File Error", strValue, 1024, strIniFile)

        Do While InStrRev(strValue, " ") = Len(strValue)
            strValue = Mid(strValue, 1, Len(strValue) - 1)
        Loop

        ' to remove a special chr in the last place
        strValue = Mid(strValue, 1, Len(strValue) - 1)
        GetIniSetting = strValue

ErrTrap:
        If Err.Number <> 0 Then Err.Raise(Err.Number, , "Error form Functions.GetIniSettings " & Err.Description)

    End Function
Posted

Gosto do exemplo do ribeiro55 usando um Dictionary, mas para ler os velhinhos ficheiros INI's (já longe de serem usados) a forma mais simples é usando as API's GetPrivateProfileString e WritePrivateProfileString, como o PauloR sugeriu.

Existem vários exemplos disponíveis na NET, mas só usava mesmo se fosse "obrigado".

Posted

Gosto do exemplo do ribeiro55 usando um Dictionary, mas para ler os velhinhos ficheiros INI's (já longe de serem usados) a forma mais simples é usando as API's GetPrivateProfileString e WritePrivateProfileString, como o PauloR sugeriu.

Existem vários exemplos disponíveis na NET, mas só usava mesmo se fosse "obrigado".

Então aconselhas um XML para guardar configurações?

  • 2 weeks later...
Posted

o ini deve guardar os valores da conection string... é so para isso que serve.....

Eventualmente podes guardar o nome do ultimo utilizador, do login.....

mas e  essencialmente usado para guardar definições da conexão

Quando te pedirem peixe.... ensina-os a Pescar!!Hum..lálálálá!!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.