CreateFile (was: Convert to VB.NET)

A

Andrew Clark

Hello,

Thanks for all replies on this subject. I still cannot get CreateFile to
retun a good value though. I went to PInvoke.net and saw the VB.NET
declaration of this function:

<DllImport("kernel32.dll", SetLastError:=True)> Private Shared Function
CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As
EFileAccess, ByVal dwShareMode As EFileShare, ByVal lpSecurityAttributes
As IntPtr, ByVal dwCreationDisposition As ECreationDisposition, ByVal
dwFlagsAndAttributes As EFileAttributes, ByVal hTemplateFile As IntPtr)
As IntPtr
End Function

VB.NET did not like the 'Private Shared' part, so I changed that to
'Public', and all the EFile* types I changed to Integer, so this is what
I end up with:

<DllImport("kernel32.dll", SetLastError:=True)> Public Function
CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As Integer,
ByVal dwShareMode As Integer, ByRef lpSecurityAttributes As IntPtr, ByVal
dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer,
ByVal hTemplateFile As IntPtr) As IntPtr
End Function

Now VB.NET does not complain at least. I put a break on this statement:

hFile = CreateFile(FileName, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)

and the values are as following:

GENERIC_READ -2147483648
IntPtr.Zero 0
OPEN_EXISTING 3
FILE_ATTRIBUTE_NORMAL 128

but still I get -1 returned! Thoughts?

Thanks,
Andrew
 
G

Guest

Why not use the .NET Framework instead of kernel32?

You can do something like this to open up a file:

Dim fs As FileStream = New FileStream("C:\filename.txt", FileMode.Open)
Dim arrayOfBytes(100) As Byte

Do While fs.Read(arrayOfBytes, 0, arrayOfBytes.Length) > 0
'Process your file
Loop

Or something like this:


Dim sw As StreamReader = File.OpenText("C:\filename.txt")
Dim fileContents As String = sw.ReadToEnd()

Take a look at the System.IO namespace for different classes for File IO.
 
G

Guest

In addition, if it's a file handle that you seek, you can also do something
like this:

Dim fs As FileStream = New FileStream("C:\filename.txt", FileMode.Open)
Dim filePtr As IntPtr = fs.Handle
hFile = filePtr.ToInt32()

Hope this helps. I haven't tested this, but it's off the top of my head.
Let me know if it works for you.
 
A

Andrew Clark

In addition, if it's a file handle that you seek, you can also do
something like this:

Dim fs As FileStream = New FileStream("C:\filename.txt",
FileMode.Open) Dim filePtr As IntPtr = fs.Handle
hFile = filePtr.ToInt32()

Hope this helps. I haven't tested this, but it's off the top of my
head. Let me know if it works for you.

Yes, I use CreateFile because I need a file handle. I will try this,
thanks!

Andrew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top