Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Visual Basic
  4. FindFirstFileEx() and Unicode

FindFirstFileEx() and Unicode

Scheduled Pinned Locked Moved Visual Basic
helptutorialcsharpalgorithms
40 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T treddie

    Dave Kreskowiak wrote:

    string variable cannot contain Unicode characters

    Yah, that was sloppy reasoning on my part. Although, I also can't explain why I was getting inconsistent behavior in what was being reported in the string. Sometimes, when I would pass the pathname to the string, it would come back with ?'s. So without having a stable situation that I can depend on, I can't come to any conclusion on what that was all about. Especially since I can't duplicate the problem. But now, what I have found is that the string holds the foreign characters just fine, but something odd happens when I send the string to an RTB and a plain TextBox. The RTB displays "\*" as "*", but the TextBox had no problem at all and correctly shows, "\*". But if I hover my mouse over the "rtb1.text =" statement in the code, it reads fine! Weird.

    Dave Kreskowiak wrote:

    You never pass a "string".

    But why do they declare strings in any function that accepts them? I've used ANSI strings before with no problem, just as MSDN suggests. The headaches happen when I get to Unicode strings.

    D Offline
    D Offline
    Dave Kreskowiak
    wrote on last edited by
    #13

    treddie wrote:

    But why do they declare strings in any function that accepts them?

    Because you're definfing the TYPE of the pointer. What kind of object does it point to? What are the rules for incrementing that pointer if needed?? If you go back to C, a "string" in it's most basic form is just a pointer to an array of type char (character). Under Windows, you can have ASCII strings and wide-character strings. Incrementing the pointer for an ASCII character just adding 1 to the pointer, but, for multi-byte characters, such as Unicode, you increment the pointer by 2 or more.

    A guide to posting questions on CodeProject[^]
    Dave Kreskowiak

    T 1 Reply Last reply
    0
    • D Dave Kreskowiak

      treddie wrote:

      But why do they declare strings in any function that accepts them?

      Because you're definfing the TYPE of the pointer. What kind of object does it point to? What are the rules for incrementing that pointer if needed?? If you go back to C, a "string" in it's most basic form is just a pointer to an array of type char (character). Under Windows, you can have ASCII strings and wide-character strings. Incrementing the pointer for an ASCII character just adding 1 to the pointer, but, for multi-byte characters, such as Unicode, you increment the pointer by 2 or more.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak

      T Offline
      T Offline
      treddie
      wrote on last edited by
      #14

      That's logical.

      1 Reply Last reply
      0
      • D Dave Kreskowiak

        treddie wrote:

        I also found through tests that the TRUE limit for Windows, is 240 characters max.

        Not quite. A fully qualifed filePATH to a file (including filename) is 248 characters max. A fileNAME (with no path information at all) is 260 characters max. Think of setting the "current directory" first before trying to access a file with a name like that. That's one way to get a filepath longer than the 248 character limit.

        treddie wrote:

        This may be a bug in Windows

        Considering that code has been around for, literally, decades, its not a bug. These are hardcoded limits in NTFS.

        A guide to posting questions on CodeProject[^]
        Dave Kreskowiak

        M Offline
        M Offline
        MicroVirus
        wrote on last edited by
        #15

        Actually, NTFS is not at all that limited. It's just that the kernel32.dll API interface is limited to those path limits. From MSDN, CreateFile page: In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces. By adding \\?\ you tell the kernel32 API to NOT do any parsing or processing on the path, and instead pass it directly on to the filesystem driver. From MSDN page on Naming Files, Paths, and Namespaces (Windows): For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. But not all functions can work with the extended paths, because some functions inherently need to do processing on the path.

        D 1 Reply Last reply
        0
        • M MicroVirus

          Actually, NTFS is not at all that limited. It's just that the kernel32.dll API interface is limited to those path limits. From MSDN, CreateFile page: In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming Files, Paths, and Namespaces. By adding \\?\ you tell the kernel32 API to NOT do any parsing or processing on the path, and instead pass it directly on to the filesystem driver. From MSDN page on Naming Files, Paths, and Namespaces (Windows): For file I/O, the "\\?\" prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. But not all functions can work with the extended paths, because some functions inherently need to do processing on the path.

          D Offline
          D Offline
          Dave Kreskowiak
          wrote on last edited by
          #16

          Yeah, I knew that. Slip of the brain when I typed it.

          A guide to posting questions on CodeProject[^]
          Dave Kreskowiak

          T 1 Reply Last reply
          0
          • D Dave Kreskowiak

            Yeah, I knew that. Slip of the brain when I typed it.

            A guide to posting questions on CodeProject[^]
            Dave Kreskowiak

            T Offline
            T Offline
            treddie
            wrote on last edited by
            #17

            OK, I'm finally getting this to work. I took the suggestion more seriously that GetLastError() might provide some insight into the problem. It wasn't anything that explicitly told me what was wrong, but it did cause me to take a much closer look at all of my declarations, and realizing that using "\\?\UNC\" was not correct...It needs to be just "\\?\". But also took to heart your comments on strings and pointers. In that regard, I found some typing problems here and there, and missed some lines that were still not rewritten for pointers. I'll post the resulting code here, shortly, after I copy my test code over to my final demo program and fix some remaining issues.

            T 1 Reply Last reply
            0
            • T treddie

              Howdie. I am researching how to use the Unicode version of FindFirstFileEx() in vb.Net and am having a heck of a time getting this to work. I had downloaded an example and it used the standard version, FindFirstFile(). I then modified the code to work with FindFirstFileEx(), instead, and got that to work, too, but only for ANSI characters (Alias "FindFirstFileExA"). But when I attempted to use the Unicode version (Alias "FindFirstFileExW"), it fails miserably. The best I have been able to do is get a non-zero return value from the function (which means it found the folder), but all the returned WFD structure contains are null strings for the folder name and alternate folder name. I have googled the problem (MSDN is of no help in this regard) and did find one reference on how to alter the function parameters to provide pointers instead of a string and the WFD structure, themselves. At any rate, here is my code for just the top half that looks for folders. The bottom half deals with searching for files, but it is just a repeat of this example, essentially. If I can get this top half to work with your help, I can certainly get the bottom half to work. I would have liked to attach a zip containing the project and the test folder I used, but it does not look like attachments are possible, here. Thanks for any help!

              Option Strict Off
              Option Explicit On
              'Option Infer Off

              Imports VB = Microsoft.VisualBasic
              Imports System.Runtime.InteropServices

              Friend Class Form1
              Inherits System.Windows.Forms.Form

              'Private Declare Function FindFirstFileExW Lib "kernel32.dll" Alias "FindFirstFileExW" (ByVal lpFileName As String, ByVal fInfoLevelId As FINDEX_INFO_LEVELS, ByVal lpFindFileData As WIN32_FIND_DATA, ByVal fSearchOp As FINDEX_SEARCH_OPS, ByRef lpSearchFilter As Int32, ByVal dwAdditionalFlags As Integer) As Long
              Private Declare Function FindFirstFileExW Lib "kernel32.dll" Alias "FindFirstFileExW" (ByVal lpFileName_IntPtr As IntPtr, ByVal fInfoLevelId As FINDEX_INFO_LEVELS, ByRef lpFindFileData_IntPtr As IntPtr, ByVal fSearchOp As FINDEX_SEARCH_OPS, ByRef lpSearchFilter As Int32, ByVal dwAdditionalFlags As Integer) As Long

              Private Declare Function FindNextFileW Lib "kernel32" Alias "FindNextFileW" (ByVal hFindFile As Long, ByRef lpFindFileData As WIN32_FIND_DATA) As Integer

              Private Declare Function GetFileAttributesW Lib "kernel32" Alias "GetFileAttributesW" (ByVal lpFileName As String) As Integer

              Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile A

              T Offline
              T Offline
              TnTinMn
              wrote on last edited by
              #18

              Hi treddie, Based on my understanding of your code, I see no reason to use FindFirstFileEx versus FindFirstFile. Also, the directory filter flag option can fail silently if it is not supported and you need to check the attributes anyways if it was your intent to just recover directories. But it appears as your code is also doing these checks. Just a word of caution about interop examples you find on the web; many of these were originally done in VB6 and may not have been properly modified for DotNet types. Here are links to a reference and a tool that you may find useful in working with interop. Miscellaneous Marshaling (look at the links under "See Also") Samples[^] PInvoke Interop Assistant[^] I was bored so I tried putting together a simple TreeView file explorer that bypasses the 260 character limit. It may serve as an example for what you are trying to do. Just place a TreeView control on new WinForm project and paste this code. I used the command prompt "Subst" command to create a drive reference to a path that reached the 260 character barier and then added some more directories under that substituted drive to get to a file that had 400+ characters in it's path to test this. It appears to work. Edit: There appears to be a length limit on codeblock code.

              Imports System.Runtime.InteropServices

              Public Class Form1
              Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
              TreeView1.Nodes.Add(DriveToTreeNode("c"c))
              End Sub

              Private Sub TreeView1_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCollapse
              e.Node.Nodes.Clear()
              e.Node.Nodes.Add(New TreeNode With {.Tag = New NodeData With {.IsDirectory = True}}) ' add dummy node
              End Sub

              Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
              ' only directories can have nodes
              e.Node.Nodes.Clear()
              EnumerateDirectory(e.Node)
              End Sub

              Private Sub TreeView1_MouseDoubleClick(ByVal sender As Obje

              T T 3 Replies Last reply
              0
              • T TnTinMn

                Hi treddie, Based on my understanding of your code, I see no reason to use FindFirstFileEx versus FindFirstFile. Also, the directory filter flag option can fail silently if it is not supported and you need to check the attributes anyways if it was your intent to just recover directories. But it appears as your code is also doing these checks. Just a word of caution about interop examples you find on the web; many of these were originally done in VB6 and may not have been properly modified for DotNet types. Here are links to a reference and a tool that you may find useful in working with interop. Miscellaneous Marshaling (look at the links under "See Also") Samples[^] PInvoke Interop Assistant[^] I was bored so I tried putting together a simple TreeView file explorer that bypasses the 260 character limit. It may serve as an example for what you are trying to do. Just place a TreeView control on new WinForm project and paste this code. I used the command prompt "Subst" command to create a drive reference to a path that reached the 260 character barier and then added some more directories under that substituted drive to get to a file that had 400+ characters in it's path to test this. It appears to work. Edit: There appears to be a length limit on codeblock code.

                Imports System.Runtime.InteropServices

                Public Class Form1
                Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
                TreeView1.Nodes.Add(DriveToTreeNode("c"c))
                End Sub

                Private Sub TreeView1_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCollapse
                e.Node.Nodes.Clear()
                e.Node.Nodes.Add(New TreeNode With {.Tag = New NodeData With {.IsDirectory = True}}) ' add dummy node
                End Sub

                Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
                ' only directories can have nodes
                e.Node.Nodes.Clear()
                EnumerateDirectory(e.Node)
                End Sub

                Private Sub TreeView1_MouseDoubleClick(ByVal sender As Obje

                T Offline
                T Offline
                TnTinMn
                wrote on last edited by
                #19

                Here is the remainder of the code.

                Private Shared Function GetShortPathName(ByVal path As String) As String
                Dim sb As New System.Text.StringBuilder(1000)
                Dim len As Int32 = GetShortPathName(LongPathPrefix & path, sb, sb.Capacity)
                If len > sb.Capacity Then
                sb.Capacity = len
                GetShortPathName(LongPathPrefix & path, sb, sb.Capacity)
                End If
                Return sb.ToString().Replace(LongPathPrefix, "")
                End Function

                <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode), BestFitMapping(False)> _
                Private Class WIN32_FIND_DATA
                <MarshalAs(UnmanagedType.U4)> Public dwFileAttributes As IO.FileAttributes
                <MarshalAs(UnmanagedType.U4)> Private ftCreationTime_dwLowDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Private ftCreationTime_dwHighDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Private ftLastAccessTime_dwLowDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Private ftLastAccessTime_dwHighDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Private ftLastWriteTime_dwLowDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Private ftLastWriteTime_dwHighDateTime As UInt32
                <MarshalAs(UnmanagedType.U4)> Public nFileSizeHigh As UInt32
                <MarshalAs(UnmanagedType.U4)> Public nFileSizeLow As UInt32
                <MarshalAs(UnmanagedType.U4)> Public dwReserved0 As UInt32
                <MarshalAs(UnmanagedType.U4)> Public dwReserved1 As UInt32

                  &#39; Note: by changing the cFileName size constant from 260 to 32767 to handle long
                  &#39; path names, it appears that cAlternateFileName always returns blank
                  &#39; if the ShortPathName is needed, then use the GetShortPathName function
                  &#39; http://msdn.microsoft.com/en-us/library/windows/desktop/aa364989%28v=vs.85%29.aspx
                   &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=32767)&gt; Public cFileName As String
                   &lt;MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)&gt; Public cAlternateFileName As String
                
                  Public Function CreationTime() As DateTime
                     Return DateTime.FromFileTime(MergeToInt64(ftCreationTime\_dwLowDateTime, ftCreationTime\_dwHighDateTime))
                  End Function
                  Public Function LastAccessTime() As DateTime
                     Return DateTime.FromFileTime(MergeToInt64(ftLastAccessTim
                
                1 Reply Last reply
                0
                • T TnTinMn

                  Hi treddie, Based on my understanding of your code, I see no reason to use FindFirstFileEx versus FindFirstFile. Also, the directory filter flag option can fail silently if it is not supported and you need to check the attributes anyways if it was your intent to just recover directories. But it appears as your code is also doing these checks. Just a word of caution about interop examples you find on the web; many of these were originally done in VB6 and may not have been properly modified for DotNet types. Here are links to a reference and a tool that you may find useful in working with interop. Miscellaneous Marshaling (look at the links under "See Also") Samples[^] PInvoke Interop Assistant[^] I was bored so I tried putting together a simple TreeView file explorer that bypasses the 260 character limit. It may serve as an example for what you are trying to do. Just place a TreeView control on new WinForm project and paste this code. I used the command prompt "Subst" command to create a drive reference to a path that reached the 260 character barier and then added some more directories under that substituted drive to get to a file that had 400+ characters in it's path to test this. It appears to work. Edit: There appears to be a length limit on codeblock code.

                  Imports System.Runtime.InteropServices

                  Public Class Form1
                  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
                  TreeView1.Nodes.Add(DriveToTreeNode("c"c))
                  End Sub

                  Private Sub TreeView1_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCollapse
                  e.Node.Nodes.Clear()
                  e.Node.Nodes.Add(New TreeNode With {.Tag = New NodeData With {.IsDirectory = True}}) ' add dummy node
                  End Sub

                  Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
                  ' only directories can have nodes
                  e.Node.Nodes.Clear()
                  EnumerateDirectory(e.Node)
                  End Sub

                  Private Sub TreeView1_MouseDoubleClick(ByVal sender As Obje

                  T Offline
                  T Offline
                  treddie
                  wrote on last edited by
                  #20

                  But FindFirstFile() cannot handle Unicode, as far as MSDN seems to suggest.

                  T 1 Reply Last reply
                  0
                  • T treddie

                    OK, I'm finally getting this to work. I took the suggestion more seriously that GetLastError() might provide some insight into the problem. It wasn't anything that explicitly told me what was wrong, but it did cause me to take a much closer look at all of my declarations, and realizing that using "\\?\UNC\" was not correct...It needs to be just "\\?\". But also took to heart your comments on strings and pointers. In that regard, I found some typing problems here and there, and missed some lines that were still not rewritten for pointers. I'll post the resulting code here, shortly, after I copy my test code over to my final demo program and fix some remaining issues.

                    T Offline
                    T Offline
                    treddie
                    wrote on last edited by
                    #21

                    One hickup...I need to deal with a C type, LPWSTR. When I research how to get this in vb.Net, I do not find any consistent explanation of how to deal with marshaling unmanaged types. There are no real-world examples and what MSDN offers is cryptic at best. Here is my best guess that does not show any syntax errors:

                    Dim LPWSTR As UnmanagedType
                    Dim MyUnicodePointer As New MarshalAsAttribute(LPWSTR)

                    D 1 Reply Last reply
                    0
                    • T treddie

                      But FindFirstFile() cannot handle Unicode, as far as MSDN seems to suggest.

                      T Offline
                      T Offline
                      TnTinMn
                      wrote on last edited by
                      #22

                      Where in the documentation does it suggest that? Quite the opposite is suggested in http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx[^]

                      Quote:

                      In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

                      T 1 Reply Last reply
                      0
                      • T TnTinMn

                        Where in the documentation does it suggest that? Quite the opposite is suggested in http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx[^]

                        Quote:

                        In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

                        T Offline
                        T Offline
                        treddie
                        wrote on last edited by
                        #23

                        Damn. I swear to gawd I saw it say you needed to use the Ex version to make it happen. Somewhere along the line I got messed up there. Too many questions all at once, I guess. But now that I know that, my overly-verbose usage should still work...I just have to keep track of extra arguments. Also, it is a good exercise in understanding both, since I may in the future need to use the Ex function. I haven't had a chance yet, today, to run your example.

                        T 1 Reply Last reply
                        0
                        • T treddie

                          Damn. I swear to gawd I saw it say you needed to use the Ex version to make it happen. Somewhere along the line I got messed up there. Too many questions all at once, I guess. But now that I know that, my overly-verbose usage should still work...I just have to keep track of extra arguments. Also, it is a good exercise in understanding both, since I may in the future need to use the Ex function. I haven't had a chance yet, today, to run your example.

                          T Offline
                          T Offline
                          TnTinMn
                          wrote on last edited by
                          #24

                          Quote:

                          Damn. I swear to gawd I saw it say you needed to use the Ex version to make it happen.

                          I blame it all on micro-blackhole that make one jump from one parallel universe to another just to screw with your mind when the minor differences bite you in the behind. :laugh: All I can say is that you are making an effort to learn and that is a rare and beautiful thing to see in a forum these days. :)

                          T 1 Reply Last reply
                          0
                          • T TnTinMn

                            Quote:

                            Damn. I swear to gawd I saw it say you needed to use the Ex version to make it happen.

                            I blame it all on micro-blackhole that make one jump from one parallel universe to another just to screw with your mind when the minor differences bite you in the behind. :laugh: All I can say is that you are making an effort to learn and that is a rare and beautiful thing to see in a forum these days. :)

                            T Offline
                            T Offline
                            treddie
                            wrote on last edited by
                            #25

                            Thanks, man! It can be frustrating, but it is more frustrating to stay confused and not see the frikkin light! :)

                            1 Reply Last reply
                            0
                            • T treddie

                              One hickup...I need to deal with a C type, LPWSTR. When I research how to get this in vb.Net, I do not find any consistent explanation of how to deal with marshaling unmanaged types. There are no real-world examples and what MSDN offers is cryptic at best. Here is my best guess that does not show any syntax errors:

                              Dim LPWSTR As UnmanagedType
                              Dim MyUnicodePointer As New MarshalAsAttribute(LPWSTR)

                              D Offline
                              D Offline
                              Dave Kreskowiak
                              wrote on last edited by
                              #26

                              An LPWSTR is just a Long Pointer to a Wide character String. You're just marshalling a normal string from .NET to the function your calling. Usually, you don't have to do anything special in your function Declaration other than tell it that the paramter is a String.

                              A guide to posting questions on CodeProject[^]
                              Dave Kreskowiak

                              T 1 Reply Last reply
                              0
                              • D Dave Kreskowiak

                                An LPWSTR is just a Long Pointer to a Wide character String. You're just marshalling a normal string from .NET to the function your calling. Usually, you don't have to do anything special in your function Declaration other than tell it that the paramter is a String.

                                A guide to posting questions on CodeProject[^]
                                Dave Kreskowiak

                                T Offline
                                T Offline
                                treddie
                                wrote on last edited by
                                #27

                                I'm confused. The function requires a pointer to a wide string, so you can't use 'As String' as a passed argument to the function FindFirstFileEx(). You have to use 'As LWPSTR' or, if I understand you correctly, 'As Long'. If that is true, then I have to wrap the string in a 'long' pointer, which for a 64bit platform would translate to Int32 (or rather, IntPtr), since a win32 function can only accept 32bits arguments and parameters. If that is true, then my existing marshal should be correct:

                                Dim MyStringPtr As Long = Marshal.StringToHGlobalAuto(MyString)
                                

                                But when I pass MyStringPtr to FindFileEx(), I only get back the first character in a Unicode folder/file name, and then, only when the first character in the string happens to be in the ANSI range.

                                A 1 Reply Last reply
                                0
                                • T treddie

                                  I'm confused. The function requires a pointer to a wide string, so you can't use 'As String' as a passed argument to the function FindFirstFileEx(). You have to use 'As LWPSTR' or, if I understand you correctly, 'As Long'. If that is true, then I have to wrap the string in a 'long' pointer, which for a 64bit platform would translate to Int32 (or rather, IntPtr), since a win32 function can only accept 32bits arguments and parameters. If that is true, then my existing marshal should be correct:

                                  Dim MyStringPtr As Long = Marshal.StringToHGlobalAuto(MyString)
                                  

                                  But when I pass MyStringPtr to FindFileEx(), I only get back the first character in a Unicode folder/file name, and then, only when the first character in the string happens to be in the ANSI range.

                                  A Offline
                                  A Offline
                                  Alan N
                                  wrote on last edited by
                                  #28

                                  I haven't read all of this thread but I don't see either the Auto or Unicode character set modifiers in your external procedure declarations, which means that the default of Ansi is being applied. This could be the root cause of your string problems as UTF16 encoded strings treated as Ansi will get truncated at the first null, i.e. after the first character. See Declare statement[^] and also Calling Windows APIs[^] for examples using both Declare and DllImport. Alan.

                                  T 1 Reply Last reply
                                  0
                                  • A Alan N

                                    I haven't read all of this thread but I don't see either the Auto or Unicode character set modifiers in your external procedure declarations, which means that the default of Ansi is being applied. This could be the root cause of your string problems as UTF16 encoded strings treated as Ansi will get truncated at the first null, i.e. after the first character. See Declare statement[^] and also Calling Windows APIs[^] for examples using both Declare and DllImport. Alan.

                                    T Offline
                                    T Offline
                                    treddie
                                    wrote on last edited by
                                    #29

                                    That basically has been my conclusion, though I don't know how to fix it yet. I figured SOMETHING had to be cutting the returned string short, and I know that the input string is getting to memory correctly, because I can retrieve it just fine. So that leaves the WIN32_FIND_DATA structure as the culprit. Documentation says the following declaration is required:

                                     Public cFileName As String
                                    

                                    And for my string pointer, I used: Dim lpFileName_IntPtr As Long = Marshal.StringToHGlobalAuto(lpFileName_str) I experimented with changing MAX_PATH to 32767 rather than 260, but alone by itself it does nothing. And anyway, that is a max character length issue, not an ANSI vs. wide character issue. So I feel that the problem is with declaring cFileName, correctly. That was where I was at when I saw your post. I do not know how to squeeze some martialing in there to account for a wide string.

                                    1 Reply Last reply
                                    0
                                    • T TnTinMn

                                      Hi treddie, Based on my understanding of your code, I see no reason to use FindFirstFileEx versus FindFirstFile. Also, the directory filter flag option can fail silently if it is not supported and you need to check the attributes anyways if it was your intent to just recover directories. But it appears as your code is also doing these checks. Just a word of caution about interop examples you find on the web; many of these were originally done in VB6 and may not have been properly modified for DotNet types. Here are links to a reference and a tool that you may find useful in working with interop. Miscellaneous Marshaling (look at the links under "See Also") Samples[^] PInvoke Interop Assistant[^] I was bored so I tried putting together a simple TreeView file explorer that bypasses the 260 character limit. It may serve as an example for what you are trying to do. Just place a TreeView control on new WinForm project and paste this code. I used the command prompt "Subst" command to create a drive reference to a path that reached the 260 character barier and then added some more directories under that substituted drive to get to a file that had 400+ characters in it's path to test this. It appears to work. Edit: There appears to be a length limit on codeblock code.

                                      Imports System.Runtime.InteropServices

                                      Public Class Form1
                                      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
                                      TreeView1.Nodes.Add(DriveToTreeNode("c"c))
                                      End Sub

                                      Private Sub TreeView1_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCollapse
                                      e.Node.Nodes.Clear()
                                      e.Node.Nodes.Add(New TreeNode With {.Tag = New NodeData With {.IsDirectory = True}}) ' add dummy node
                                      End Sub

                                      Private Sub TreeView1_BeforeExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand
                                      ' only directories can have nodes
                                      e.Node.Nodes.Clear()
                                      EnumerateDirectory(e.Node)
                                      End Sub

                                      Private Sub TreeView1_MouseDoubleClick(ByVal sender As Obje

                                      T Offline
                                      T Offline
                                      treddie
                                      wrote on last edited by
                                      #30

                                      I built your project, but when run, the treeview stays blank.

                                      T 2 Replies Last reply
                                      0
                                      • T treddie

                                        I built your project, but when run, the treeview stays blank.

                                        T Offline
                                        T Offline
                                        TnTinMn
                                        wrote on last edited by
                                        #31

                                        Edit: I deleted the upload, forgot I was in the middle of trying an ASCII version. Will repost a link once I get it back to Unicode. That's strange. I tried running it on a low privilege account and it run fine on Vista/32 bit. In case anything got messed up while I was trying to post the code(I had some issues) I've uploaded the project (VS2008) to: http://sdrv.ms/18SnASR This version is a bit different because I've been playing with it bit this evening. You will also find the syntax for the FindFirstFileEx function in the scraps.txt file. Try un-commenting the code in this block:

                                        If hFile.DangerousGetHandle.ToInt32 = -1 Then
                                        ' just ignoring errors for this demo, most common is 5 - Access Denied
                                        ' System Error Codes
                                        ' http://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
                                        Dim [error] As Int32 = Marshal.GetLastWin32Error()
                                        Stop
                                        Return
                                        Else

                                        and see what error code, if any, you are getting.

                                        1 Reply Last reply
                                        0
                                        • T treddie

                                          I built your project, but when run, the treeview stays blank.

                                          T Offline
                                          T Offline
                                          TnTinMn
                                          wrote on last edited by
                                          #32

                                          Here is the updated project link that I mentioned in my previous post. http://sdrv.ms/13fhQi8[^]

                                          T 2 Replies Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups