Is there a way to use data from a read file in VB as an active string variable? - vbscript

I'm trying to make a script that reads file data in a text file as a string then can be called as another variable. I've been working on it for a while.
Code that will open the file:
Option Explicit
Dim fso, BC1
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
MsgBox BC1.ReadLine
BC1.Close
I need to take the 1 line of data read from this textfile and set it as another variable in string format (ie: Dim Variable1 As String = BC1 data). Any ideas? If I can get the data I want from the file as a string, the rest of my script will execute like it should.

To save all file data in a text file to strBC1 variable (string variant):
Option Explicit
Dim fso, BC1, strBC1
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
strBC1 = BC1.ReadAll
BC1.Close
To read a text file line by line and save 1st non-empty line to strLine variable (string variant):
Option Explicit
Dim fso, BC1, strLine
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
Do Until BC1.AtEndOfStream
strLine = BC1.Readline
If strLine <> "" Then
Exit Do 'stops looping and transfers control
' to the statement immediately following the Loop
End If
Loop
BC1.Close

Related

Read a line from several .txt files and write them into created file

I have a quite simple task.
There is a folder which contains several files with different extensions. I need to make a script which will find all files with .txt extension in this folder, read first line from every file and then write all first lines in newly created file.
For now, I've ended up with something like this:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f, colFiles , objFile
Dim tFolder, tFile
Dim lineToCopy, fileContents
Dim input, output
Set tFolder = fso.GetFolder("C:\Temp")
Set tFile = tFolder.CreateTextFile("test.txt", true)
Set f = fso.GetFolder("D:\Folder")
Set colFiles = f.Files
For Each objFile in colFiles
If LCase(fso.GetExtensionName(objFile.name)) = "txt" Then
Set input = fso.OpenTextFile(LCase(objFile.name))
If Not input.AtEndofStream Then lineToCopy = input.ReadLine
input.close
output = fso.OpenTextFile(tFolder, True)
output.WriteLine lineToCopy
output.close
End If
Next
WScript.sleep 60000000
When activated, .vbs file tells me he couldn't find the file from that line:
Set input = fso.OpenTextFile(LCase(objFile.name))
I suppose that happens because IF LCASE<...> block doesn't understand folder contents as .txt files. Where am I wrong and what is needed to be done to solve that problem?
Kindly yours,
Richard
Use the full .Path of the file for OpenTextFile or get the stream via OpenAsTextStream. Use tFile instead of repeatedly creating output. Delete all the risky/cargo cult fat:
Option Explicit
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim tFile : Set tFile = fso.CreateTextFile(fso.BuildPath(".\", "test.txt"))
Dim oFile
For Each oFile in fso.GetFolder("..\data").Files
If LCase(fso.GetExtensionName(oFile.Path)) = "txt" Then
' Dim input: Set input = fso.OpenTextFile(LCase(oFile.Path))
Dim input: Set input = oFile.OpenAsTextStream()
If Not input.AtEndofStream Then tFile.WriteLine input.ReadLine()
input.Close
End If
Next
tFile.Close
Looks like I've found my own decision:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f, colFiles , objFile
Dim tFolder, tFile
Dim lineToCopy, readFile
Set tFolder = fso.GetFolder("C:\Temp")
Set tFile = tFolder.CreateTextFile("test.txt", true)
Set f = fso.GetFolder("D:\Scripting Games 2008\Beginner")
Set colFiles = f.Files
For Each objFile in colFiles
If LCase(fso.GetExtensionName(objFile.name)) = "txt" Then
REM Preceding passage finds all .txt files in selected folder
Set readFile = objFile.OpenAsTextStream
lineToCopy = ""
Do Until lineToCopy <> "" Or readfile.atEndOfStream
lineToCopy = Trim(readFile.ReadLine)
Loop
REM Extracts first line of the text, if it is not empty
tFile.WriteLine objFile.name & ": " & lineToCopy
End If
Next
Still, thanks for the answers. I've found some interesting solutions which well be of use some time.
Kindly yours,
Richard

VBScript create and open a new file

I try to make a script in VBScript for PowerAMC.
And I've got an error.
I checked all elements to make a file with the content (XSD file):
private Sub writeInFile(pathFolder, pathFile, val)
Output "WriteInFile["&pathFolder&pathFile&"]"
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile(pathFolder&pathFile, true)
If (fso.FileExists(pathFolder&pathFile)) Then
MyFile.WriteLine(val)
Else
ouput "File can't be create"
End If
MyFile.Close
end Sub
And the file exists with good content, but if I try to read it with:
public Function readFile(path)
'Declare variables
Dim objFSO, objReadFile, contents
'Set Objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.OpenTextFile(path, 1, false)
'Read file contents
contents = objReadFile.ReadAll
'Close file
objReadFile.close
'Cleanup objects
Set objFSO = Nothing
Set objReadFile = Nothing
readFile = contents
End Function
I get that : "ÿþ<" for only content, but if I try to read a file that is not created by the previous function, it runs perfectly.
I think the problem comes from Unicode format,
take a look at this => FileSystemObject - Reading Unicode Files

Read and write into a file using VBScript

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.
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
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")
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.
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
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
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
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.
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
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

How to read from a text file using VBScript?

I am looking to see a simple way to read from and write to a text file using VBScript.
I think this is an acceptable method for writing to a file.
Dim f,
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateTextFile("C:\test.txt", True, True)
f.WriteLine("Data to Add to file.")
f.Close
However, I would like to know how to read from a file in a similar fashion.
Use first the method OpenTextFile, and then...
either read the file at once with the method ReadAll:
Const ForReading = 1
Dim file, content
Set file = fso.OpenTextFile("C:\test.txt", ForReading)
content = file.ReadAll
or line by line with the method ReadLine:
Const ForReading = 1
Dim dict, file, row, line
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", ForReading)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close

How do I replace text from one file with text from another file using vbscript?

How do I replace text from one file with text from another file using vbscript?
The text being replaced is somewhere in the middle of the file.
filea.txt:
hello cruel world
fileb.txt:
cruel
filec.txt:
happy
will make sResult = "hello happy world" after the following has executed.
Dim oFSO
Dim sFileAContents
Dim sFileBContents
Dim sFileCContents
Dim sResult
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileAContents = oFSO.OpenTextFile("c:\filea.txt").ReadAll()
sFileBContents = oFSO.OpenTextFile("c:\fileb.txt").ReadAll()
sFileCContents = oFSO.OpenTextFile("c:\filec.txt").ReadAll()
sResult = Replace(sFileAContents, sFileBContents, "")
FileToSearch is the file with the text you want to search for replacement
FileReplaceText is the file containing the replacement text
Edit the value of the variable strTextToFind to contain the text you are searching for and replacing
Dim objFSO
Dim strFileToSearch
Dim strFileReplaceText
Dim strTextToFind
Dim strTextToSearch
Dim strTextReplaceText
Dim strFinalText
strFileToSearch = "C:\FileToSearch.txt"
strFileReplaceText = "C:\FileReplaceText.txt"
strTextToFind = "text to search for here"
Set objFSO = CreateObject("Scripting.FileSystemObject")
strTextToSearch = objFSO.OpenTextFile(strFileToSearch).ReadAll()
strFileReplaceText = objFSO.OpenTextFile(strFileReplaceText).ReadAll()
strFinalText = Replace(strTextToSearch, strTextToFind, strFileReplaceText)
If you want to write this final text back out to a file then add this code:
Const ForWriting = 2
Dim strFileFinalOutput
strFileFinalOutput = "C:\FileFinalOutput.txt"
Set objTextFile = objFSO.OpenTextFile(strFileFinalOutput, ForWriting, True)
objTextFile.Write strFinalText
objTextFile.Close
Set objTextFile = Nothing
This code reads the entire file into memory (.ReadAll) and may experience problems with very large files. In this case, the code can be edited to read/search/replace/write the data line by line.
If the text you are searching for is not continuous and all on the same line then the search/replace process is more involded and this code will need additional work to handle it.

Resources