Leggere\Scrivere un testo da un file di testo

by enrico 23. February 2009 13:13

Io non mi ricordo mai come leggere o scrivere un file di testo: ho ritenuto quindi di creare un post con due funzioni che possono essere utili.

   1: Imports System.IO
   2:  
   3: ' funzione di lettura del contenuto di un file
   4: Public Function GetFileContents(ByVal FullPath As String, _
   5:        Optional ByRef ErrInfo As String = "") As String
   6:         Dim strContents As String
   7:         Dim objReader As StreamReader
   8:         Try
   9:             objReader = New StreamReader(FullPath)
  10:             strContents = objReader.ReadToEnd()
  11:             objReader.Close()
  12:             Return strContents
  13:         Catch Ex As Exception
  14:             ErrInfo = Ex.Message
  15:         End Try
  16: End Function
  17:  
  18: ' funzione per il salvataggio di un testo in un file
  19: Public Function SaveTextToFile(ByVal strData As String, _
  20:      ByVal FullPath As String, _
  21:        Optional ByVal ErrInfo As String = "") As Boolean
  22:  
  23:         Dim Contents As String
  24:         Dim bAns As Boolean = False
  25:         Dim objReader As StreamWriter
  26:         Try
  27:             objReader = New StreamWriter(FullPath)
  28:             objReader.Write(strData)
  29:             objReader.Close()
  30:             bAns = True
  31:         Catch Ex As Exception
  32:             ErrInfo = Ex.Message
  33:         End Try
  34:         Return bAns
  35: End Function

 

Per poter utilizzare questo codice si può seguire il seguente esempio:

   1: sContents = GetFileContents("C:\test.txt", sErr)
   2: If sErr = "" Then
   3:    Debug.WriteLine("File Contents: " & sContents)
   4:    ' salva in un file differente
   5:    bAns = SaveTextToFile(sContents, "D:\Test.txt", sErr)
   6:    If bAns Then
   7:       Debug.WriteLine("File Saved!")
   8:    Else
   9:       Debug.WriteLine("Error Saving File: " & sErr)
  10:    End If
  11: Else
  12:    Debug.WriteLine("Error retrieving file: " & sErr)
  13: End If

Buon lavoro!

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , ,

vb.net | Tricks & Tips | windowsform

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by Esia Software 1.4.0.0

Informazioni sull'autore

Sono un cittadini di Trieste, ho 33 anni e faccio lo sviluppatore nella mia azienda che si chiama Esia Software.

Commenti recenti

Comment RSS

Post recenti

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Info legali

Le opinioni espresse in questo blog sono strettamente personali e ogni persona è responsabile dei commenti che inserisce.

RecentComments

Comment RSS