.net里长短文件名的解决办法open in new window

当我用Path.GetTempFileName()函数去取一个目录名时,竟然得到这样的结果:C:\DOCUME~1\Vitami~1。。。应该是c:\Documents and Settings\VitaminC.net的。找了半天,最后在GotDotNet找到了结果,把代码贴出来大家看看:

using System;
using System.Text;
using System.Runtime.InteropServices;

namespace ShellPathNameConvert
{
    /// <summary>
    /// Converts file and directory paths to their respective
    /// long and short name versions.
    /// </summary>
    /// <remarks>This class uses InteropServices to call GetLongPathName and GetShortPathName</remarks>
    public class Convert
    {
        [DllImport("kernel32.dll")]
        static extern uint GetLongPathName(string shortname, StringBuilder longnamebuff, uint buffersize);

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

        /// <summary>
        /// The ToShortPathNameToLongPathName function retrieves the long path form of a specified short input path
        /// </summary>
        /// <param name="shortName">The short name path</param>
        /// <returns>A long name path string</returns>
        public static string ToLongPathName(string shortName)
        {
            StringBuilder longNameBuffer = new StringBuilder(256);
            uint bufferSize = (uint)longNameBuffer.Capacity;

            GetLongPathName(shortName, longNameBuffer, bufferSize);

            return longNameBuffer.ToString();
        }

        /// <summary>
        /// The ToLongPathNameToShortPathName function retrieves the short path form of a specified long input path
        /// </summary>
        /// <param name="longName">The long name path</param>
        /// <returns>A short name path string</returns>
        public static string ToShortPathName(string longName)
        {
            StringBuilder shortNameBuffer = new StringBuilder(256);
            int bufferSize = shortNameBuffer.Capacity;

            int result = GetShortPathName(longName, shortNameBuffer, bufferSize);

            return shortNameBuffer.ToString();
        }
    }
}

运行结果

Current directory:
D:\Documents and Settings\Administrator\桌面\ShellPathNameConvert\ShellPathNameC
onvertTest\bin\Debug

Short path name:
D:\DOCUME~1\ADMINI~1\桌面\SHELLP~1\SHELLP~2\bin\Debug

Long path name:
D:\Documents and Settings\Administrator\桌面\ShellPathNameConvert\ShellPathNameC
onvertTest\bin\Debug

附带上作者的说明

ShellPathNameConvert will allow you to convert to and from Long and Short paths. It's common for the Windows shell to send you a short path if your application takes command line arguments. However, it's not always convenient to work with the short path names and .NET provides no built in way to get the long path nam

posted on 2005-02-03 01:58 维生素C.NET 阅读(2074) 评论(1)

Contributors: FHL