C#调用windows api 函数GetShortPathName

本文介绍了如何在C#中直接调用Windows API函数GetShortPathName来获取文件的短路径。通过使用DllImport属性和extern关键字,详细展示了调用过程,包括方法声明、参数处理和错误检查。
  
其实我们的议题应该叫做C#如何直接调用非托管代码,通常有2种方法:
1.  直接调用从 DLL 导出的函数。
2.  调用 COM 对象上的接口方法
我主要讨论从dll中导出函数,基本步骤如下:
1.使用 C# 关键字staticextern声明方法。
2DllImport属性附加到该方法。DllImport属性允许您指定包含该方法的 DLL 的名称
3.如果需要,为方法的参数和返回值指定自定义封送处理信息,这将重写 .NET Framework 的默认封送处理。
好,我们开始
1.首先我们查询MSDN找到GetShortPathName的定义
The GetShortPathName function retrieves the short path form of the specified path.
DWORD GetShortPathName(
  LPCTSTR lpszLongPath,
  LPTSTR lpszShortPath,
  DWORD cchBuffer
);
 public class CShortPath
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetShortPathName(
            [MarshalAs(UnmanagedType.LPTStr)]string path,
            [MarshalAs(UnmanagedType.LPTStr)]StringBuilder short_path,
            int short_len
            );

        public static string GetShortPath(string name)
        {
            int lenght = 0;

            lenght = GetShortPathName(name, null, 0);
            if (lenght == 0)
            {
                //new nghmp.GenericErrorForm("Can't get short path name", name, true);
                return name;
            }
            StringBuilder short_name = new StringBuilder(lenght);
            lenght = GetShortPathName(name, short_name, lenght);
            if (lenght == 0)
            {
                //new nghmp.GenericErrorForm("Can't get short path name", name, true);
                return name;
            }
            return short_name.ToString();
        }//GetShortPath
    }//class CShortPath


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值