c# - 在 c# 中使用 kernel32.dll 缩短长文件路径名
问题描述
我正在尝试将长文件路径转换为短文件路径。尝试使用下面提到的 kernel32.dll 中可用的所有 GetShortPathName 签名。但是都返回一个空字符串而不是一个短文件路径。在win 10的64位机器上使用ac# windows app(.net framework 4.6.1)进行测试。请告诉我如何获取一个短文件路径。下面是我的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern uint GetShortPathName(
[MarshalAs(UnmanagedType.LPTStr)]
string lpszLongPath,
[MarshalAs(UnmanagedType.LPTStr)]
StringBuilder lpszShortPath,
uint cchBuffer);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern uint GetShortPathName(string lpszLongPath, char[] lpszShortPath, int cchBuffer);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetShortPathNameW",
SetLastError = true)]
static extern int GetShortPathName(string pathName, System.Text.StringBuilder shortName, int
cbShortName);
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
string longFilePath = @"C:\E\Authors files\GOLD\ddd Retail Leases\ddd Owned or Co-Owned Centres (including Property Income Fund Properties) – Managed by ddd\Garden City Booragoon (WA)\Specialty Leases & Deeds\Shop 12A\35120-#5337137, v1 _VICProduction1_ - Shop xxx - Garden City, Booragoon - D.C.K Australia Pty Ltd t_as Lovisa - Executed Deed of Assignment and Variation of Lease and Consent to Assignment - WorkSite Acrobat Integration.pdf";
string s1 = ShortPath(longFilePath);
string s2=ToShortPathName(longFilePath);
string s3 = GetShortPathName(longFilePath);
}
public static string ToShortPathName(string longName)
{
uint bufferSize = 256;
StringBuilder shortNameBuffer = new StringBuilder((int)bufferSize);
GetShortPathName(longName, shortNameBuffer, bufferSize);
return shortNameBuffer.ToString();
}
public string ShortPath(string longpath)
{
char[] buffer = new char[256];
GetShortPathName(longpath, buffer, buffer.Length);
return new string(buffer);
}
public static string GetShortPathName(string longFileName)
{
uint bufferSize = 256;
StringBuilder shortNameBuffer = new StringBuilder((int)bufferSize);
uint result = GetShortPathName(longFileName, shortNameBuffer, bufferSize);
return shortNameBuffer.ToString();
}
}
}
解决方案
推荐阅读
- monitoring - 联邦普罗米修斯中的连接丢失
- reactjs - 如何使用替换为 React 中字符串的特定部分添加颜色?
- python - 使用 python 库将 pem 转换为 pfx 证书类型
- ios - 如何为溶解效果编写 sceneKit 着色器修改器
- javascript - javascript获取表格中所有图像的自然宽度/高度
- android - 如何更新 RecyclerView 对数据进行排序?
- r - 使用 R 中的 model.matrix 函数拟合 PCA
- glsl - 如何避免片段着色器中的额外计算
- c++ - 如何为多种 C++ 类型创建编译时检查?
- node.js - NodeJS将对象json打印到html