Jean-Guy2000
April 23rd, 2001, 12:32 PM
HI, I am trying to use the API to read a entire file to a string, I need a fast way to open text and binary files. I write this function but it's crashing saying the memory cannot be written during the ReadFile DLL call. I know this is normally un-allocated buffer but I cannot seem to track the problem down, has anyone else done this? whats wrong with this code?
Public Function get_file_contents() As String
Dim fileContents As String
Dim lResult As Long
Dim lFileHandle As Long
Dim lTempFile As Long
Dim tSecurity As SECURITY_ATTRIBUTES
Dim tOverlapped As OVERLAPPED
Dim lFileSize As Long
Dim lBytesRead As Long
lFileHandle = CreateFile(FilePath, GENERIC_READ, 0, tSecurity, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, lTempFile)
If lFileHandle = INVALID_HANDLE_VALUE Then 'Did file open?
get_file_contents = "" 'Nope!
Exit Function 'we are done
End If
lResult = GetFileSize(lFileHandle, lFileSize) 'Get size of file
If lResult = INVALID_FILE_SIZE Then 'Did we get the size?
lResult = CloseHandle(lFileHandle) 'Close file handle
Exit Function 'Exit
End If
lFileSize = lResult 'Calc file size
fileContents = String(lFileSize, Chr(0)) 'allocate buffer
lResult = ReadFile(lFileHandle, fileContents, lFileSize, lBytesRead, tOverlapped)
lResult = CloseHandle(lFileHandle) 'Close filehandle
get_file_contents = fileContents
End Function
Jean-Guy
Public Function get_file_contents() As String
Dim fileContents As String
Dim lResult As Long
Dim lFileHandle As Long
Dim lTempFile As Long
Dim tSecurity As SECURITY_ATTRIBUTES
Dim tOverlapped As OVERLAPPED
Dim lFileSize As Long
Dim lBytesRead As Long
lFileHandle = CreateFile(FilePath, GENERIC_READ, 0, tSecurity, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, lTempFile)
If lFileHandle = INVALID_HANDLE_VALUE Then 'Did file open?
get_file_contents = "" 'Nope!
Exit Function 'we are done
End If
lResult = GetFileSize(lFileHandle, lFileSize) 'Get size of file
If lResult = INVALID_FILE_SIZE Then 'Did we get the size?
lResult = CloseHandle(lFileHandle) 'Close file handle
Exit Function 'Exit
End If
lFileSize = lResult 'Calc file size
fileContents = String(lFileSize, Chr(0)) 'allocate buffer
lResult = ReadFile(lFileHandle, fileContents, lFileSize, lBytesRead, tOverlapped)
lResult = CloseHandle(lFileHandle) 'Close filehandle
get_file_contents = fileContents
End Function
Jean-Guy