2

I was troubleshooting a problem where CreateFile couldn't open an existing named pipe when I found CreateFile() didn't work well with the filename parameter. My code is:

Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileW" ( _
ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, _
ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal hTemplateFile As Long) As Long

pipeHandle = CreateFile("C:\\test.txt", GENERIC_READ Or GENERIC_WRITE, 0&, 0&, CREATE_ALWAYS, 0&, 0&)

It does not create the file in C:\, instead, it creates a file in the current VB working directory, with a garbled filename. It seems CreateFile cannot recognize and parse the given filename string.

Why is this happening? I'm using VB6 on Windows 7 (used some trick to install it). Could that be causing the problem?

animuson
  • 53,861
  • 28
  • 137
  • 147
Charlie
  • 764
  • 2
  • 13
  • 24
  • 1
    Why two \\ in the file name? More than likely your problem stems from that. You can't just copy/paste examples, you need to know what is going on. For example the \ is not escaped in VB6 though it is in many of the curly-brace languages. – Bob77 May 26 '11 at 02:21
  • \\ really is one of the problems. I did not know VB6 does not escape \, that's why I was pondering the correctness of "\\.\pipe\testpipe". Now the main problem proved to be unicode/ansi. I tried CreateFileA and it worked. Thanks for your info. – Charlie May 26 '11 at 02:53
  • 1
    @Charlie : if an answer helped you, don't forget to accept it as the answer, and maybe upvote! (your profile says you haven't upvoted a single answer despite asking 9 questions) – Mitch Wheat May 26 '11 at 03:05
  • @Mitch, I always wanted to vote to notify the problem is solved and to appreciate the help, but it always said I needed a reputation of 15 to vote. That's why I could not. – Charlie May 26 '11 at 03:28
  • @Charlie: np . I've upvoted this question, so your a bit closer! – Mitch Wheat May 26 '11 at 03:44

1 Answers1

4

It's been a long time, but I think this is an ansi/unicode thing. Try the CreateFileA function and see what happens. (Also, IIRC, you don't escape the \ ....although again it's been about 7 years since I seriously coded with VB6.)

MJB
  • 9,352
  • 6
  • 34
  • 49
  • Thanks a lot @MJB. CreateFileA worked. Now I know although VB6 String is unicode, it converts strings to ANSI when passing in parameters. – Charlie May 26 '11 at 02:55
  • Now, note there is a way to get CreateFileW working.... I recall doing it,and maybe someone else will jump in.If ansi is good enough for your app,though, great. – MJB May 26 '11 at 04:09
  • 2
    Note: I looked it up and if filename is declared as long and you pass StrPtr(yourStringFilename) as that parameter, CreateFileW might work too. – MJB May 26 '11 at 06:56