Reading and writng a text file...

pekt2s

Member
Joined
Apr 26, 2007
Messages
15
Programming Experience
Beginner
Hi guyz... i would like to ask if you can spare me a little bit of your knowledge about on how to read and write text file... thanks guyz...

pekt2s..!
 
Might I suggest searching MSDN, Google and other forum posts here before asking something as simple an operation as this? :)

VB.NET:
Function ReadTextFile(Path As String) As String
    Dim fsReader As New System.IO.StreamReader(Path)
    Dim ReturnValue = fsReader.ReadToEnd()
    fsReader.Close()
    Return ReturnValue
End Function

Sub WriteTextFile(Path As String, TextToWrite As String)
    Dim fsWriter As New System.IO.StreamWriter(Path)
    fsWriter.Write(TextToWrite)
    fsWriter.Close()
End Sub
 
VB.NET:
Function ReadTextFile(Path As String) As String
    Dim fsReader As New System.IO.StreamReader(Path)
    Dim ReturnValue = fsReader.ReadToEnd()
    fsReader.Close()
    Return ReturnValue
End Function

should be:
VB.NET:
Function ReadTextFile(Path As String) As String
  If IO.File.Exist(Path) = True Then
    Dim fsReader As New System.IO.StreamReader(Path)
    Dim ReturnValue As String = fsReader.ReadToEnd()
    fsReader.Close()
    Return ReturnValue
  Else
    Throw New FileNotFoundException(Path)
  End If
End Function
 
It was meant to be an example for starters, not conventionally-correct as I would do in the very production development environment I code in every day.

" = True" should be removed if that is the case. :)
 
u can use following for reading and writing line by line...

.......
VB.NET:
dim objStramReader as streamReader =nothing
dim objStreamWritter as StreamWritter=File.Createtext(FilePath)
dim strLine as String=nothing

objStramReader =new streamReader(file.OpenRead(PathWithFileName))

while(objStramReader.peek<>-1 )
  strLine=objStramReader.ReadLine()
  objStreamWritter.WriteLine(strLine)
end while

objStreamWritter.Close()
objStramReader .close()
 
Last edited by a moderator:
if you're wanting an exact copy of the file, why read it and write it line by line?

System.IO.File.Copy() will do the trick, just pass it the source file and the new file path and name.
 
Back
Top