file exists then replace if doesnt create
can any one please help on this scenario
If file exists it should replace the text and if file doesnt exists it should create the file.
If file exists it should replace the text and if file doesnt exists it should create the file.
0 Comments
[ + ] Show comments
Answers (2)
Please log in to answer
Posted by:
murali.bhat
14 years ago
Dim objFSO, objFile, strNewText
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(<File Path>, 1)
If objFSO.FileExists (<Path of File>) then
strNewText = Replace(objFile.ReadAll,"<Text to Replace>")
objFile.Close
Set objFile = objFSO.OpenTextFile(<File Path>, 2)
objFile.Write strNewText
objFile.Close
Else
objFile.Close
objFSO.CreateTextFile("<Path to the File>")
End If
Set objFSO = Nothing
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(<File Path>, 1)
If objFSO.FileExists (<Path of File>) then
strNewText = Replace(objFile.ReadAll,"<Text to Replace>")
objFile.Close
Set objFile = objFSO.OpenTextFile(<File Path>, 2)
objFile.Write strNewText
objFile.Close
Else
objFile.Close
objFSO.CreateTextFile("<Path to the File>")
End If
Set objFSO = Nothing
Posted by:
captain_planet
14 years ago
errrm.....I'm not entirely sure you need to use the 'FileExists' method. OpenTextFile has a parameter which creates the file if it doesn't exist....[;)]
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName
Set fso = CreateObject("Scripting.FileSystemObject")
' Open the file for output.
FileName = "c:\temp\testfile.txt"
Set MyFile = fso.OpenTextFile(FileName, ForWriting, True)
' Write to the file.
MyFile.WriteLine "This is a test"
'Close file
MyFile.Close
Set MyFile = Nothing
![](/build/static/general/appdeploy_logo.png)
so that the conversation will remain readable.