The OpenTextFile is overriding opened text file by clearing it - vbscript

I am currently having a problem with OpenTextFile. I created a script over a year ago. Recently, the script started giving me problems. It's clearing the first text file and giving me an error.
Set objArgs = WScript.Arguments
myFile = objArgs(0)
numberofTXT = objArgs(1)
line = objArgs(2)
Set f = CreateObject("Scripting.FileSystemObject").OpenTextFile(myFile, line)
d = f.ReadLine
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write d & vbCrLf
objFile.Close
This is a super basic script I wrote to explain my issue. Takes in 3 files as arguments. For example LOL.txt, Hi.txt, and a specific line of LOL.txt (Why did 13-year-old me give examples using the word Lol, oh my gosh). This is meant to read the first file and write the data from the first file to the second file.
This issue was due to my current understanding (when I posted this) and not knowing what documentation was. I was self-taught. Please make sure to read the documentation if you have any issues with OpenTextFile and make sure your arguments are correct for the function.

Read and apply the OpenTextFile Method reference:
Opens a specified file and returns a TextStream object that can be
used to read from, write to, or append to the file.
Syntax
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
object   Required. Object is always the name of a FileSystemObject.
filename Required. String expression that identifies the file to open.
iomode   Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create   Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value
is True if a new file is created, False if it isn't created. If
omitted, a new file isn't created.
format   Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as
Unicode, TristateFalse = 0 to open the file as ASCII,
TristateUseDefault = -2 to open the file as the system default). If
omitted, the file is opened as ASCII.
Settings
The iomode argument can have any of the following settings:
Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ForWriting 2 Open a file for writing.
ForAppending 8 Open a file and write to the end of the file.
Read CreateTextFile Method reference as well. Then, the following commented code snippet could help:
Const ForReading = 1
Set objArgs = WScript.Arguments
myFile = objArgs(0) ' file to read
numberofTXT = objArgs(1) ' file to write
line = objArgs(2) ' line serial number to write into output file
' (or number of lines?)
Set objFSO = CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
Set f = objFSO.OpenTextFile(myFile, ForReading)
lineindex = 1
Do until f.AtEndOfStream
d = f.ReadLine
if lineindex = line Then ' only take the line-th line
objFile.Write d & vbCrLf ' or objFile.WriteLine d
Exit Do ' transfers control to the statement immediately following Loop statement
End If
lineindex = lineindex + 1
Loop
objFile.Close
f.Close

Related

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

Windows script host error 800A0046

I'm receiving the following error when I run my program:
Script: C: My Folder\Tracking Macro.vbs
Line: 70
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error
Here is the code.
' Set constants for reading, writing, and appending files
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Sets up the object variables.
Dim objExcel, objFSO, objTextFile, objCSVFile
' Sets up the string variables.
Dim strTextFile, strHeadLine, strTextLine, strCSVFile
' Sets up the all the string variables for the program.
Dim Desktop, todaysDate, usageDate, myDay, myMonth, myYear
'This creates the required Objects
Set objExcel = CreateObject("Excel.application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Desktop = WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\" & "Desktop"
' Set date for date stamp in file name and sheet name
todaysDate = Date()
myMonth = Month(todaysDate)
If Len(myMonth)=1 Then myMonth="0" & myMonth
myDay = Day(todaysDate)
If Len(myDay)=1 Then myDay="0" & myDay
myYear = Right(Year(todaysDate), 2)
usageDate = myMonth & myDay & myYear
' Set up the origin and destination files
strTextFile = (Desktop & "\MacroTracker.txt")
strCSVFile = "C: My Folder\TrackingTesting" & usageDate & ".csv"
strHeadLine = "Macro Name,User ID,Ran At,Contracted Rate,BHVN,Set Number,Provider TIN,Billed Charge,Service Code"
Set objTextFile = objFSO.OpenTextFile(strTextFile)
' Read the entire origin file
Do Until objTextFile.AtEndOfStream
strTextLine = objTextFile.ReadLine
Loop
If (objFSO.FileExists(strCSVFile)) Then
' Create object for appending current TXT file to CSV file
Set objCSVFile = objFSO.OpenTextFile(strCSVFile, ForAppending, True)
' Write an append line of data to the CSV file
objCSVFile.WriteLine strTextLine
Else
' Create CSV file to write to with today's date
Set objCSVFile = objFSO.CreateTextFile(strCSVFile, True)
' Create object for appending current TXT file to CSV file
Set objCSVFile = objFSO.OpenTextFile(strCSVFile, ForAppending, True)
' Write initial header for the CSV file
objCSVFile.WriteLine strHeadLine
' Write an append line of data to the CSV file
objCSVFile.WriteLine strTextLine
End If
' Wait for file to be written to
Wscript.Sleep 600
' Delete origin file to prevent user tampering
objFSO.DeleteFile(strTextFile)
Line 70 is the very last line where I'm deleting the text file. According to every help site I've seen, this is EXACTLY how it should be typed. I checked the permissions of the file...I have full control, so I should be able to delete it. It's only meant to be a temp file, not something that stores info for long periods of time.
I've checked Microsoft and all other help sites for the error code and have not found any solutions that can help me. I'm hoping someone may have ran into a similar instance and found a resolution.
Your file is still open. You need to add this:
objTextFile.Close
somewhere before you try to delete it. I would put it right after you're done using the file.

Reg - Error Input Past End of File - VbScript

I wrote a simple program to write and read data from text file using FileSystemObject, but it doesn't work and gives me a runtime error:
Input Past End of File.
Kindly let me know the mistake I made here.
'Here is the Program -
Dim Fso 'Reference obect to File system
Dim TxtObj 'Reference to Text stream object
Dim Txt 'Reference to Text stream object to open file
Dim i 'To Read Text in file
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Txtobj = Fso.CreateTextFile("C:\Users\ACER\Desktop\Project Folder\NewText_3.txt")
Txtobj.Write("Hello")
Txtobj.Close
Set Txt = Fso.OpenTextFile("C:\Users\ACER\Desktop\Project Folder\NewText_3.txt",1)
Do while Txt.AtEndOfStream<>1
i = Txt.Read(1)
Loop
Msgbox i
Txt.close
Option Explicit ' safety belt
Const FSpec = "14481096.txt" ' dry the file name
Dim Fso 'Reference object to File system
Set Fso = CreateObject("Scripting.FileSystemObject")
Dim TxtObj 'Reference to Text stream object (used for rwrite and read)
Set Txtobj = Fso.CreateTextFile(FSpec)
Txtobj.WriteLine "Hello"
Txtobj.Close
Dim Letter 'To Read Text in file (each letter)
Set Txtobj = Fso.OpenTextFile(FSpec) ' ForReading is the default, no need for magic number 1)
Do Until Txtobj.AtEndOfStream ' never compare boolean values against boolean literals
' or - worse - values of other types you *hope* VBScript
' will convert correctly
Letter = Txtobj.Read(1) ' letter
WScript.Echo "got", Letter
Loop
Txtobj.Close
output:
cscript 14481096.vbs
got H
got e
got l
got l
got o
got <-- aka cr
got <-- aka lf (in case you are wondering)
Extra hint:
>> WScript.Echo CInt(True), CInt(False)
>>
-1 0
>>

Script help needed editing ini file

I'm trying to edit one line in an ini file. DeviceName=APPLE to DeviceName="The User Input". I have it almost there from bits and pieces across the internet. It works except the end result is my file jwalk.ini with the correct entry after user input but the ini file has been renamed to just .ini, no jwalk before ini. I must be missing something. The file jwalk.ini already will exist I just need to edit it with the new user input and leave the file named the same.
My Script:
Const ForReading = 1
Const ForWriting = 2
Const OpenAsASCII = 0
Const CreateIfNotExist = True
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Open existing file for read access.
strInput = "c:\MyFolder\jwalk.ini"
Set objInput = objFSO.OpenTextFile(strInput, ForReading)
' Prompt for device name.
strDeviceName = InputBox("Enter devicename", "JWalk PC Name or Session Name")
' Specify the new file name.
strOutput = "c:\MyFolder\" & strComputer & ".ini"
' Create new file with write access.
Set objOutput = objFSO.OpenTextFile(strOutput, _
ForWriting, CreateIfNotExist, OpenAsASCII)
' Process input file.
Do Until objInput.AtEndOfStream
' Read next line of the input file.
strLine = objInput.ReadLine
' Search for line to be modified.
' Make search case insensitive.
If (InStr(LCase(strLine), "devicename=") > 0) Then
' Replace the line.
' You could also modify the line.
strLine = "devicename=" & strDeviceName
End If
' Write line to the output file.
objOutput.WriteLine strLine
Loop
' Clean up.
objInput.Close
objOutput.Close
' Delete the original file.
objFSO.DeleteFile(strInput)
Any ideas? Thanks.
If you'd have used Option Explicit, you'd have been told that
strOutput = "c:\MyFolder\" & strComputer & ".ini"
uses the undefined/uninitialized variable strComputer.
Here you are passing "strComputer" as a var, but never set it's value:
' Specify the new file name.
strOutput = "c:\MyFolder\" & strComputer & ".ini"
If you are trying to get the computer name you could consider this:
' Specify the new file name.
strOutput = "c:\MyFolder\" & GetComputerName() & ".ini"
Function GetComputerName()
Dim ob
Set ob = Wscript.CreateObject("Wscript.Network")
GetComputerName = ob.ComputerName
Set ob = nothing
End Function

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