Dot-Net

在.net中轉換為短路徑的標準方法

  • September 29, 2015

尋找標準的防錯誤方法將“長名稱”(例如“C:\Documents and settings”)轉換為等效的“短名稱”“C:\DOCUME~1”

我需要這個來執行我的 C# 應用程序的外部程序。如果我用“長名稱”中的路徑提供它,它會失敗。

即使您將長文件路徑括在引號中,外部程序是否也會失敗?如果外部應用程序支持,這可能是一種更簡單的方法。

例如

myExternalApp "C:\Documents And Settings\myUser\SomeData.file"

如果您準備開始呼叫 Windows API 函式,則 GetShortPathName() 和 GetLongPathName() 提供此功能。

http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html

   const int MAX_PATH = 255;

   [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
   public static extern int GetShortPathName(
       [MarshalAs(UnmanagedType.LPTStr)]
        string path,
       [MarshalAs(UnmanagedType.LPTStr)]
        StringBuilder shortPath,
       int shortPathLength
       );

   private static string GetShortPath(string path) {
       var shortPath = new StringBuilder(MAX_PATH);
       GetShortPathName(path, shortPath, MAX_PATH);
       return shortPath.ToString();
   }

引用自:https://stackoverflow.com/questions/258367