Monday, October 30, 2017

To set/update the value of the variable into the text file

Function fnSet_Value_Into_TextFile(strFilePath,varName, varValue)
'function to set/update the value of the variable into the text file
On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
'Path of the file to be modified
'strFilePath = Environment("Env_TestData_TextFile")
'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'If specfied text file does not exist, create the text file and set the data
If Not objFSO.FileExists(strFilePath) Then
Set  objTextFile = objFSO.CreateTextFile(strFilePath, true)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
Exit Function
End If
'Get the file to be read.
'if fhe file is already created but no data available, then set the data
Set objGetFile = objFSO.GetFile(strFilePath)
If objGetFile.Size = 0 Then
Set objTextFile = objGetFile.OpenAsTextStream(ForAppending,False)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
Exit Function
End If
'If text file exist and the variable exist in it, then update its value
'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
Flag = 0
Dim var_SplitData()
Counter = 0
'This code will read all the lines in the Config file
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
ReDim Preserve var_SplitData(Counter)
var_found = Instr(1,strNextLine,varName,1)
If var_found> 0 Then
Flag = 1
var_SplitData(Counter) = varName & " = " & varValue
Else
var_SplitData(Counter) = strNextLine
End If
Counter = Counter + 1
Loop
'This code will close the file after reading
objTextFile.Close
'Write data into the file
Set objTextFile = objGetFile.OpenAsTextStream(ForWriting,False)
For var_Loop = 0 to UBound(var_SplitData)
objTextFile.WriteLine var_SplitData(var_Loop)
Next
objTextFile.Close
If Flag = 0 Then
Set objTextFile = objGetFile.OpenAsTextStream(ForAppending,False)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
End If
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while set the value into Text file", "Set value to text file is  failed")
fnGet_Value_From_TextFile = ""
End If
End Function

No comments:

Post a Comment