Like us on Facebook

February 8, 2015

How to Open/Read/Write/Appened a File through FileSystemObject using VB Script

  2/08/2015 No comments

We shall use File System object to open a File and read its content through 'Read','ReadAll'
and  'ReadLine' methods of a File, opened in Reading mode.
We can open a file in three different mode for reading ,writing and appending.Const is a reserved
keyword in VB Script which is used to declare constant variables in script.OpenTextFile 
is method of FileSystemObject which is used to open files.

1.'Example of Read method of File object, Read Method takes parameter as number of
specified characters that should be read

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim objFso, objFile, Msg
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile= objFso.OpenTextFile("D:\Music\myTextFile.txt", ForWriting, True)
'Write content into the file 
objFile.Write "Hello world!"
Set objFile = objFso .OpenTextFile("D:\Music\myTextFile.txt", ForReading) 
Msgbox objFile.Read(5) 'display first five characters of file

OutPut:
 '2.ReadLine() method reads first line in file and returns resulting string

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim objFso, objFile, Msg
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile= objFso.OpenTextFile("D:\Music\myTextFile.txt", ForWriting, True)
'Write content into the file 
objFile.Write "Hello world!"
Set objFile = objFso .OpenTextFile("D:\Music\myTextFile.txt", ForReading) 
Msgbox objFile.ReadLine()

Output:

3.ReadAll() method of File object returns all the lines available in File
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim objFso, objFile, Msg
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile= objFso.OpenTextFile("D:\Music\myTextFile.txt", ForWriting, True)
'Write content into the file
objFile.Write "Hello world!"
'write another line to understand better
objFile.WriteBlankLines(1)
objFile.Write"Hello Leela!"
Set objFile = objFso.OpenTextFile ("D:\Music\myTextFile.txt", ForReading)
Msgbox objFile.ReadAll()

OutPut :


Author: Vikas Pandey

He is a software and web developer working for renowned European investment bank.He loves to share knowledge through blogging whatever he knows and encourages others as well to share the same to make world a better place to live.

0 comments:

.
© 2014-2015 Informational Digit : How-To & Tech Guides. The content is copyrighted to Vikas Pandey and may not be reproduced on other websites. WP themonic converted by Bloggertheme9.
TOP