Find the GetShortPathName method signature,
DWORD GetShortPathName (LPCTSTR tpszlongpath,tptstr lpszshortpath,dword cchbuffer);
unmanaged and managed data type correspondence:
LPCTSTR String
LPTSTR StringBuilder
DWORD int
Import rules for DllImport:
1, the method name and win API exactly the same. If a completely different method name is displayed when called in C #, you need to introduce the EntryPoint property and display it with an alias.
2. The function needs to declare the public static extern type in addition to the DllImport class modifier.
3. function return values and parameters must be exactly the same as the API that is invoked.
4, must introduce System.Runtime.InteropServices namespace.
Code:
Copy Code code as follows:
Using System.Runtime.InteropServices;
public class Test
{
[DllImport ("Kernel32.dll", charset=charset.auto,entrypoint= "Getshort")]
public static extern int GetShortPathName (
[MarshalAs (UNMANAGEDTYPE.LPTSTR)] String Path,
[MarshalAs (UNMANAGEDTYPE.LPTSTR)] StringBuilder ShortPath,
int shortpathlength);
}
The path to Kernel32.dll in code calls is not written because DllImport finds the DLL in the following three order:
1, exe directory, 2, System32 directory, 3, environment variables directory.
MarshalAs is an optional type because each data type has a default marshaling behavior that indicates how to marshal data between managed and unmanaged code, which can be used for parameters, fields, and return values. In most cases, this property can satisfy most unmanaged data types only with the UnmanagedType enumeration type, such as by default the characters are passed into the DLL as BSTR, and you can use MarshalAs to designate a string as LPTSTR, LPWStr, or LPSTR.
DllImport Optional Attribute Interpretation
EntryPoint can use a different name for the method, using the alias
CharSet function call using Unicode or ANSI
ExactSpelling False, which means that the compiler chooses to use Unicode or ANSI
Callingconvetnion its arguments to indicate the convention that the entry point calls; do not specify default for CALLINGCONVENTION.WINAPI
PreserveSig indicates whether the method signature should be retained or converted, and when converted it is converted to a signature of an additional output parameter named RetVal with an HRESULT return value and the return value, which defaults to true.
setlasterror Specifies whether the last error is persisted, and the default is False