Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

c# call Win32 API for long file paths?

How would I go about calling Win32 API for long file paths, the only thing I want to do is get a list of all the files in that directory (recursivly)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to use Win32 calls you will first have to use DllImport to import the kernel, the syntax is like something like this and you must do this for every method you want to use(this is all un-tested pseudo-code that only describes the concept), the code example converts your paths to UNC paths so you can have long file paths:

    using Microsoft.Win32.SafeHandles;
    ...
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            static extern SafeHandleMinusOneIsInvalid FindFirstFileW(string lpFileName, IntPtr lpFindFileData);

    ...

            public String FindFirstFile(string filepath)
            {
                // If file path is disk file path then prepend it with \?
                // if file path is UNC prepend it with \?UNC and remove \ prefix in unc path.
                if (filepath.StartsWith(@""))
                    filepath = @"\?UNC" + filepath.Substring(2, filepath.Length - 2);
                else
                    filepath = @"\?" + filepath;
...
                SafeHandleMinusOneIsInvalid ret = FindFirstFileW(filepath, lpFindFileData);
...
            }

After you call FindFirstFile you must call FindNextFile for the next file in the directory, and then finally FindClose; for a complete example about how to list files in a directory using the Win32 kernel look here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...