■■■

2016年4月3日日曜日

GetShortPathNameで短いパスを取得する方法

GetShortPathNameで短いパスをス得する方法
VB.NET
<System.Runtime.InteropServices.DllImport("kernel32.dll", _
    CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
Private Shared Function GetShortPathName( _
    <System.Runtime.InteropServices.MarshalAs( _
        System.Runtime.InteropServices.UnmanagedType.LPTStr)> _
    ByVal lpszLongPath As String, _
    <System.Runtime.InteropServices.MarshalAs( _
        System.Runtime.InteropServices.UnmanagedType.LPTStr)> _
    ByVal lpszShortPath As System.Text.StringBuilder, _
    ByVal cchBuffer As Integer) As Integer
End Function

Public Shared Function GetShortPath(ByVal path As String) As String
    Dim sb As New System.Text.StringBuilder(1023)
    Dim ret As Integer = GetShortPathName(path, sb, sb.Capacity)
    If ret = 0 Then
        Throw New Exception("短いファイル名の取得に失敗しました。")
    End If
    Return sb.ToString()
End Function

Private Sub btn1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles btn1.Click
    Console.WriteLine(GetShortPath("C:\Documents and Settings"))
End Sub
C#
[System.Runtime.InteropServices.DllImport("kernel32.dll",
    CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern uint GetShortPathName(
    [System.Runtime.InteropServices.MarshalAs(
        System.Runtime.InteropServices.UnmanagedType.LPTStr)]
    string lpszLongPath,
    [System.Runtime.InteropServices.MarshalAs(
        System.Runtime.InteropServices.UnmanagedType.LPTStr)]
    System.Text.StringBuilder lpszShortPath,
    uint cchBuffer);

public static string GetShortPath(string path)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder(1024);
    uint ret = GetShortPathName(path, sb, (uint)sb.Capacity);
    if (ret == 0)
        throw new Exception("短いファイル名の取得に失敗しました。");
    return sb.ToString();
}

private void btn1_Click(object sender, EventArgs e)
{
    Console.WriteLine(GetShortPath("C:\\Documents and Settings"));
}

■■■