Monday, June 25, 2012

VB^ Code for File OPerations

Public Function DeleteFile(strPath As String) As String
On Error GoTo Error
If FSO.FileExists(strPath) Then
FSO.DeleteFile (strPath)
End If
Error:
MsgBox ("DeleteFile : " & Err.Description)
End Function
Public Function MoveFile(ByVal strSrcPath As String, ByVal strDestPath As String) As String
On Error GoTo Error
If FSO.FileExists(strSrcPath) Then
FSO.MoveFile strSrcPath, strDestPath

End If
Error:
MsgBox ("MoveFile : " & Err.Description)
End Function
Public Function ReadFile(ByVal strFilePath As String) As String
On Error GoTo Error
Dim strOutput As String
If FSO.FileExists(strFilePath) = False Then
Exit Function
End If
Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount As Long
nFileNum = FreeFile
Open strFilePath For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
   Line Input #nFileNum, sNextLine
   'do something with it
   'add line numbers to it, in this case!
   sNextLine = sNextLine & vbCrLf
   sText = sText & sNextLine
Loop
strOutput = sText

Error:
MsgBox ("ReadFile : " & Err.Description & strOutput)
End Function
Public Function WriteFile(strFilePath As String, strToWriteFilePath As String) As String
On Error GoTo Error
Dim strOutput As String
If fso.FileExists(strFilePath) = False Then
Exit Function
End If
Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount As Long
nFileNum = FreeFile
Open strFilePath For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
   Line Input #nFileNum, sNextLine
  
   sNextLine = sNextLine & vbCrLf
   sText = sText & sNextLine
Loop
strOutput = sText
Dim newFIle
Set fso = CreateObject("Scripting.FileSystemObject")
 Set newFIle = fso.CreateTextFile(strToWriteFilePath, True, False)
newFIle.Write strOutput


Error:
MsgBox ("WriteFile : " & Err.Description & strOutput)
End Function