VBScript create and open a new file - vbscript

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

Related

Create a text file in %temp% and write content in it using vbs

Basically, I want to create a new file and write in it in a directory on the PC, pointed to by the %TEMP% variable. However, the revised code below does not work:
Dim oFile
Dim shell
Set oShell = CreateObject("WScript.Shell")
user = oShell.ExpandEnvironmentStrings("%Temp%")
Set oFile = CreateObject("Wscript.Shell")
Set oFile = oFile.CreateTextFile("%Temp%\d.txt")
oFile.WriteLine "here is my contant"
oFile.Close
Error Message:
run time error
line no: 3
object required
Old Code
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
FileName = "%TEMP%\myfile.txt"
Set tf = fso.CreateTextFile(FileName, True)
If I use the file name "C:\myfile.txt" it works fine.
Error Message:
Path not found
In VBA, you can just use Environ("TEMP") to expand the Environment variable - if this does not work in VBScript, you may need to bind the WScript.Shell object and use the ExpandEnvironmentStrings property instead, like so:
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%TEMP%") & "\myfile.txt"
Set oShell = Nothing
Following from comments below
Here is a "fully fixed" code:
'Declare variables/objects first
Dim fso AS Object, oFile AS Object
Dim oShell AS Object, FileName AS String
'This bit turns "%TEMP%" into a real file path
Set oShell = CreateObject("WScript.Shell")
FileName = oShell.ExpandEnvironmentStrings("%Temp%\d.txt")
Set oShell = Nothing 'Tidy up the Objects we no longer need
'This bit creates the file
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.CreateTextFile(FileName)
oFile.WriteLine "here is my content"
oFile.Close
Set oFile = Nothing 'Tidy up the Objects we no longer need
Set fso = Nothing 'Tidy up the Objects we no longer need
you can use Environ("temp") to write to C:\Users\[username]\AppData\Local\Temp

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

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

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 to navigate to multiple URLs listed in text file

I am trying to create a Vbscript to go through a text file containing different URLs and navigate to each URL using WshShell.Run. I am currently getting: "Object Required: urllist" Error.
Sorry I am new to Vbscript not sure where to go from here.
The urllist.txt is stored in the same directory.
Here is what I have so far:
dim listFile
dim WshShell
dim fName
Set fso = CreateObject("Scripting.FileSystemObject")
Set listFile = fso.OpenTextFile(urllist.txt)
Set WshShell = WScript.CreateObject("WScript.Shell")
Dim fso
'do while not listFile.AtEndOfStream
fName = listFile.ReadLine()
Return = WshShell.Run("iexplore.exe " & fName, 1)
'loop
You missed quote-mark. Next line:
Set listFile = fso.OpenTextFile(urllist.txt)
Should be:
Set listFile = fso.OpenTextFile("urllist.txt")

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

Resources