26

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1) 

This opens the file only for reading but I am unable to write anything and when I use this code:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)

I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.

I am really new to VBScript. I am only familiar with C concepts. Is there any link to really get me started with VBScript?

I guess I need to have a good knowledge of the objects and properties concepts.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

9 Answers9

23

You can create a temp file, then rename it back to original file:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
Do Until ts.AtEndOfStream
    strLine = ts.ReadLine
    ' do something with strLine 
    objOutFile.Write(strLine)
Loop
objOutFile.Close
ts.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile 

Usage is almost the same using OpenTextFile:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
strTemp = "c:\test\temp.txt"
Set objFile = objFS.OpenTextFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)    
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    ' do something with strLine 
    objOutFile.Write(strLine & "kndfffffff")
Loop
objOutFile.Close
objFile.Close
objFS.DeleteFile(strFile)
objFS.MoveFile strTemp,strFile 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • Only point is that you should use `objOutFile.WriteLine(Inp)` to output the same lines. – ib11 Apr 30 '19 at 03:28
13

Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:

  • Option Explicit to help detect typos in variables.
  • Function and Sub to improve readilbity and reuse
  • Const so that well known constants are given names

Here's some code to read and write text to a text file:

Option Explicit

Const fsoForReading = 1
Const fsoForWriting = 2

Function LoadStringFromFile(filename)
    Dim fso, f
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename, fsoForReading)
    LoadStringFromFile = f.ReadAll
    f.Close
End Function

Sub SaveStringToFile(filename, text)
    Dim fso, f
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename, fsoForWriting)
    f.Write text
    f.Close
End Sub

SaveStringToFile "f.txt", "Hello World" & vbCrLf
MsgBox LoadStringFromFile("f.txt")
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
  • 2
    Both functions need the "f.Close" method so that the files do not remain opened. – Rich Feb 28 '14 at 18:03
  • 1
    `.ReadAll` seems to have a filesize limit that other methods don't. Or at least my script crashes on files over 1GB or so... –  Nov 10 '16 at 21:10
  • Do not use `ReadAll` for large files, but instead use the `TextStream` object to buffer the reads / writes. – user692942 Apr 21 '20 at 10:10
6

Don't think so...you can only use openTextFile for reading (1), writing (2), or appending (8). Reference here.

If you were using VB6 instead of VBScript, you could do:

Open "Filename" [For Mode] [AccessRestriction] [LockType] As #FileNumber

Using the Random mode. For example:

Open "C:\New\maddy.txt" For Random As #1
Daniel F. Thornton
  • 3,687
  • 2
  • 28
  • 41
  • I am really new to vbscripting.I am just familiar with my C concepts. Can anyone please suggest me any link to get really get my vbscripting started. I guess i need to have a good knowledge on the objects and properties concepts.. Any suggestions?? –  Jul 17 '09 at 11:29
  • Here is a nice tutorial from W3Schools: http://www.w3schools.com/Vbscript/vbscript_intro.asp – Daniel F. Thornton Jul 17 '09 at 11:38
  • pianoman,Thanks a lot..I had gone through the link already and just tells abt the basic operations.I want to get into a bit more deep like the usage of objects,classes.I am really new to these terms as such. –  Jul 17 '09 at 11:40
  • Here a fairly-detailed explanation of those terms: http://www.4guysfromrolla.com/webtech/092399-1.shtml – Daniel F. Thornton Jul 17 '09 at 11:48
6

You could open two textstreams, one for reading

Set filestreamIn = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,1)

and one for appending

Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt,8,true)

The filestreamIN can read from the begining of the file, and the filestreamOUT can write to the end of the file.

Tester101
  • 8,042
  • 13
  • 55
  • 78
2

You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the

 'this gives you an excel app
 oExcel = CreateObject("Excel.Application")

 'this opens a work book of your choice, just set "Target" to a filepath
 oBook = oExcel.Workbooks.Open(Target)

 'how to read
 set readVar = oExcel.Cell(1,1).value
 'how to write
 oExcel.Cell(1,2).value = writeVar

 'Saves & Closes Book then ends excel
 oBook.Save
 oBook.Close
 oExcel.Quit

sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you

WR D
  • 39
  • 11
  • 'Writing to individual cells in Excel is excruciatingly slow. Use array instead. Sorry for no formatting. Dim vArray As Variant Dim lEndRow As Long, lEndCol As Long With oSheet With .UsedRange lEndRow = .Cells(.Cells.Count).Row lEndCol = .Cells(.Cells.Count).Column End With vArray = .Range(.cells(1, "A"), .Cells(lEndRow, lEndCol)).Value ' Manipulate it and put it back. .Range(.cells(1, "A"), .Cells(lEndRow, lEndCol)).Value = vArray End With – j2associates Sep 08 '22 at 21:15
1

You could also read the entire file in, and store it in an array

Set filestreamIN = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",1)
file = Split(filestreamIN.ReadAll(), vbCrLf)
filestreamIN.Close()
Set filestreamIN = Nothing

Manipulate the array in any way you choose, and then write the array back to the file.

Set filestreamOUT = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Test.txt",2,true)

for i = LBound(file) to UBound(file)
    filestreamOUT.WriteLine(file(i))
Next

filestreamOUT.Close()
Set filestreamOUT = Nothing 
Tester101
  • 8,042
  • 13
  • 55
  • 78
1

Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.

0

Below is some simple code to execute this:

sLocation = "D:\Excel-Fso.xls"
sTxtLocation = "D:\Excel-Fso.txt"
Set ObjExl = CreateObject("Excel.Application")
Set ObjWrkBk = ObjExl.Workbooks.Open(sLocation)
Set ObjWrkSht = ObjWrkBk.workSheets("Sheet1")
ObjExl.Visible = True
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSOFile = FSO.CreateTextFile (sTxtLocation)
sRowCnt = ObjWrkSht.usedRange.Rows.Count
sColCnt = ObjWrkSht.usedRange.Columns.Count
For iLoop = 1 to sRowCnt
  For jLoop = 1 to sColCnt 
    FSOFile.Write(ObjExl.Cells(iLoop,jLoop).value) & vbtab 
  Next
Next

Set ObjWrkBk = Nothing
Set ObjWrkSht = Nothing
Set ObjExl = Nothing
Set FSO = Nothing
Set FSOFile = Nothing
gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • Welcome to Stack Overflow! Please be careful with linking to your own content on different sites, you don't want to be a [spammer](http://stackoverflow.com/help/promotion). You should be including the majority of the content here, and use the link only as a reference. – NathanOliver Jun 30 '16 at 17:44
0

This is for create a text file

For i = 1 to 10
    createFile( i )
Next

Public Sub createFile(a)

    Dim fso,MyFile
    filePath = "C:\file_name" & a & ".txt"
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set MyFile = fso.CreateTextFile(filePath)
    MyFile.WriteLine("This is a separate file")
    MyFile.close

End Sub

And this for read a text file

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

For Each line in dict.Items
  WScript.Echo line
  WScript.Sleep 1000
Next