Write a text file from string
This is a sample program to write text file from string. The string should be well formed, The string will be written as it is. So the line breaks should be placed when prearing the string before passing it to the function.
Visual basic is a nice language to write a simple File.Io operations. It is not only simpler to write but also very easy to debug. Using this kind of helpers can improve the code re-usablity also.I have written already a lot of articles related to File operations like reading file, searching files using regular expressions.
There are various ways to read write files. I prefer the file system objects to handle the file system, As it looks very neat and easy to be handled. When ever working in file stream it is really necessary to close the stream. Otherwise it will be really not efficient.
By using the IsOverwrite parameter we can append text to the existing file. If IsOverwrite is false then the text will be written to a new text file.
Source Code
'************************************************************
'* Purpose : To create a text file from string
'*
'* Inputs : strText(String) Text to be created as a file
'* strPath(String) Path to create the text file
'* IsOverWrite(Boolean)Write mode flag Append/New
'*
'* Returns : NA
'************************************************************
Public Sub Str2Text(strText As String, _
strPath As String, _
Optional ByVal IsOverWrite As Boolean = True)
Dim stmWrite As Scripting.TextStream
Dim fso As New FileSystemObject
Dim strContent As String
On Error GoTo ErrTrap
strContent = Text2String(strPath)
Set stmWrite = fso.OpenTextFile(strPath, ForWriting, True)
stmWrite.WriteLine IIf(IsOverWrite, strText, strContent & vbCrLf & strText)
stmWrite.Close
Set stmWrite = Nothing
ErrTrap:
If Err Then Err.Raise Err.Number, , "Error form Functions.Str2Text " & Err.Description
End Sub
For Text2String function please refer the visual basic section