_llseek





VB.Net


Imports System.Runtime.InteropServices

Module _LLSeek
    Const FILE_BEGIN As Integer = 0
    Const SEEK_SET As Integer = 0

    Const GENERIC_READ = &H80000000
    Const GENERIC_WRITE = &H40000000
    Const GENERIC_EXECUTE = &H20000000
    Const GENERIC_ALL = &H10000000

    Const CREATE_NEW = 1
    Const CREATE_ALWAYS = 2
    Const OPEN_EXISTING = 3
    Const OPEN_ALWAYS = 4
    Const TRUNCATE_EXISTING = 5

    Const INVALID_HANDLE_VALUE As Int64 = -1

    <DllImport("kernel32.dll", EntryPoint:="_llseek", SetLastError:=True)>
    Private Function _llseek(hFile As IntPtr, dwDesiredPosition As Integer, dwMoveMethod As Integer) As Integer
    End Function

    <DllImport("kernel32.dll", CharSet:=CharSet.Ansi)>
    Private Function CreateFileA(lpFileName As String, dwDesiredAccess As Integer, dwShareMode As Integer, lpSecurityAttributes As IntPtr, dwCreationDisposition As Integer, dwFlagsAndAttributes As Integer, hTemplateFile As IntPtr) As IntPtr
    End Function

    Const KERNEL32 As String = "kernel32.dll"

    <DllImport(KERNEL32, EntryPoint:="_lread", CallingConvention:=CallingConvention.Winapi)>
    Private Function _lread(hFile As IntPtr, lpBuffer As Byte(), nBytesToRead As Integer) As Integer
    End Function

    <DllImport("kernel32", SetLastError:=True)>
    Private Function CloseHandle(hObject As IntPtr) As Boolean
    End Function

    Sub _llseek_Main()
        ' Open a file
        Dim hFile As IntPtr = CreateFileA("C:\kernel32\123.txt", GENERIC_READ Or GENERIC_WRITE, 0, Nothing, OPEN_EXISTING, 0, Nothing)

        If hFile.ToInt32 <> INVALID_HANDLE_VALUE Then
            Try
                ' Move the file pointer to the beginning of the file
                Dim result As Integer = _llseek(hFile, 0, FILE_BEGIN)
                Console.WriteLine("Moved to position {0}", result)

                ' Read the file
                Dim buffer(1024) As Byte
                Dim bytesRead As Integer = _lread(hFile, buffer, 1024)
                Console.WriteLine("Read {0} bytes", bytesRead)

            Finally
                ' Close the file
                CloseHandle(hFile)
            End Try
        End If
    End Sub
End Module