Jump to content

[VB.NET 2005] Escrita e leitura de *.txt


watt
 Share

Recommended Posts

Boa noite!

estou com um grande problema ...

tipo tenho este codigo

   

        Dim file As New StreamWriter("E:\Diario.txt")

        file.WriteLine("txt.Text")

        file.Close()

sempre q o corro ele escreve sp por cima da mesma linha e não quero, seria sempre na linha seguinte.

depois queria fazer algo do estilono txt

(conteudo do txt.Text) $ limitado a 10 caracteres --> + 10 espaços em branco --> uma variavel limitada a 6 caracteres

e depois ir buscar mais tarde os valores

tou sp a inventar ... será que alguem me pode dar uma ajudinha sff ?

Link to comment
Share on other sites

boas!!

posso te ajudar na parte do "e depois ir buscar mais tarde os valores"  usa o comando mid

criei um file c:\mako com isto gravado (0123456789abcdefg) depois fiz com uma textbox e um botao

e o botao com este codigo

Private Sub Command1_Click()
Dim f As Long, linha As String
f = FreeFile
Open ("c:\mako.txt") For Input As f   ' abre o file
Line Input #f, linha   ' variavel linha passa a ser o ke esta no file
text1 = Mid(linha, 1, 10) + "          " + Mid(linha, 11, 6)
End Sub

Sintaxe:  Mid(string, inicio,comprimento)

Parte               Descrição

string           -->      Uma expressão caractere do qual iremos extrair um certo número de caracteres.

inicio           -->      Posição inicial a partir da qual iremos extrair uma certa quantidade de caracteres da expressão string.

comprimento -->    Número de caracteres que desejamos extrair a partir da posição inicial . Se omitida todos os caracteres a partir de inicio serão extraidos.

epá a esta hora ja na da pra mais

fica bem

Link to comment
Share on other sites

Para acrescentar texto a um ficheiro tabem podes usar o seguinte código...

  Dim nfich, texto As String

  nfich = TextBox1.Text
  texto = TextBox2.Text
  FileOpen(1, nfich, OpenMode.Append)

  PrintLine(1, texto)

cumps.

pus assim:

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

        List.Items.Add(txt.Text)

        Dim texto As String

        texto = txt.Text

        FileOpen(1, texto, OpenMode.Append)

        PrintLine(1, texto)

        Dim file As New StreamWriter("E:\VB.NET\Tickettime\tickettime\tickettime\Diario.txt")

        file.WriteLine(txt.Text)

        file.Close()

        txt.Text = ""

    End Sub

e deu erro 🙂

Link to comment
Share on other sites

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
    Public Shared Sub Main()
        Using w As StreamWriter = File.AppendText("log.txt")
            Log("Test1", w)
            Log("Test2", w)
            ' Close the writer and underlying file.
            w.Close()
        End Using
        ' Open and read the file.
        Using r As StreamReader = File.OpenText("log.txt")
            DumpLog(r)
        End Using
    End Sub
    Public Shared Sub Log(ByVal logMessage As String, ByVal w As TextWriter)
        w.Write(ControlChars.CrLf & "Log Entry : ")
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
        w.WriteLine("  :")
        w.WriteLine("  :{0}", logMessage)
        w.WriteLine("-------------------------------")
        ' Update the underlying file.
        w.Flush()
    End Sub
    Public Shared Sub DumpLog(ByVal r As StreamReader)
        ' While not at the end of the file, read and write lines.
        Dim line As String
        line = r.ReadLine()
        While Not line Is Nothing
            Console.WriteLine(line)
            line = r.ReadLine()
        End While
        r.Close()
    End Sub
End Class

Tinhas este codigo disponivel no MSDN ...ve se te desenrascas assim

Link to comment
Share on other sites

Para acrescentar texto a um ficheiro tabem podes usar o seguinte código...

  Dim nfich, texto As String

  nfich = TextBox1.Text
  texto = TextBox2.Text
  FileOpen(1, nfich, OpenMode.Append)

  PrintLine(1, texto)

cumps.

tipo ... tenho isto


        Dim texto As String
        texto = txt.Text
        FileOpen(1, texto, OpenMode.Append)
        PrintLine(1, texto)
        FileClose(1)

        Dim file As New StreamWriter("E:\VB.NET\Tickettime\tickettime\tickettime\Diario.txt")
        file.WriteLine(txt.Text)
        file.Close()

        txt.Text = ""

e ele só me escreve na 1ª linha

Link to comment
Share on other sites

Isto é apenas um exemplo muito simples, ok...

Experimenta, cria 3 textboxes (Name, Age e Class) um botão (Escrever) e o ficheiro 666.txt.

Assumindo que o ficheiro 666.txt já existe e que tu já fizeste o parsing das textboxes, escreve o seguinte código para o botão:

Private Sub Escrever_Click()
'//Codigo adicional por exemplo para fazer o parsing das textboxes
'//verificar se o ficheiro existe etc, etc...
currentfilenum = FreeFile
Open "666.txt" For Append Access Write Lock Write As #currentfilenum
	'//Isto escreve <Name|Age|Class>, adapta a tua maneira...
	Print #currentfilenum, "<" & Trim(Name.Text) & "|" & Trim(Age.Text) & "|" & Trim(Class.Text) & ">"
Close #currentfilenum
End Sub

Vê se faz o que tu queres...

Cyas 🙂

Link to comment
Share on other sites

Oi !!!

Olha, se calhar safavas te se descarregasses o fixeiro.txt todo pra uma variavel (arrray) e depois trabalhavas os dados como queres, apagas inseres editas, isto tudo no array.

No fim é só gravares tudo no fixeiro outra vez. posso te dar uma ajuda mas em VB6 porque vbnet nao é comigo 😄

épa se poderes tão ajuda-me sff

no .net já estou a conseguir escrever e ver o que tenho no file, agora gostava de apagar uma linha, e por exemplo escrevela novamente... acredito que em breve já consiga por isto a editar os ficheiros

Link to comment
Share on other sites

Boa noite!

estou com um grande problema ...

tipo tenho este codigo

   

        Dim file As New StreamWriter("E:\Diario.txt")

        file.WriteLine("txt.Text")

        file.Close()

sempre q o corro ele escreve sp por cima da mesma linha e não quero, seria sempre na linha seguinte.

depois queria fazer algo do estilono txt

(conteudo do txt.Text) $ limitado a 10 caracteres --> + 10 espaços em branco --> uma variavel limitada a 6 caracteres

e depois ir buscar mais tarde os valores

tou sp a inventar ... será que alguem me pode dar uma ajudinha sff ?

Experimenta isto:

Imports System.IO

Public Class Form1
    Inherits System.Windows.Forms.Form

    '********* Cria/Abre o ficheiro *********
    Dim fs As New FileStream("D:\Diario.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
    Dim SwFromFile As StreamWriter = New StreamWriter(fs)


#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

        '********* para escrever no final do ficheiro *********
        fs.Position = fs.Length

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents Button1 As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.TextBox1 = New System.Windows.Forms.TextBox()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(40, 48)
        '********* Limite do tamanho da caixa de texto *********
        Me.TextBox1.MaxLength = 10
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(192, 20)
        Me.TextBox1.TabIndex = 0
        Me.TextBox1.Text = "TextBox1"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(64, 112)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(136, 40)
        Me.Button1.TabIndex = 1
        Me.Button1.Text = "Button1"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Button1, Me.TextBox1})
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '********* Escreve *********
        Me.SwFromFile.WriteLine(Me.TextBox1.Text)
        Me.SwFromFile.Flush()
    End Sub


    Protected Overrides Sub Finalize()
        '********* fechar o ficheiro *********
        SwFromFile.Close()
        MyBase.Finalize()
    End Sub

End Class

Para ler usa o StreamReader Members

Só que em vez de WriteLine tens ReadLine e não precisas do flush.

Para escolher a linha que queres ler -> mexes no fs.Position para a posição inicial e um ciclo for até a linha que queres ler.

Link to comment
Share on other sites

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
 Share

×
×
  • 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.