C# 方法将长路径名转换为短路径,返回null

C# 方法将长路径名转换为短路径,返回null,c#,asp.net-mvc,C#,Asp.net Mvc,如果文件名很长,我会尽量确保可以下载该文件。这是我正在使用的类 public class ShortFileName { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern int GetShortPathName( [MarshalAs(UnmanagedType.LPTStr)] string path, [MarshalAs(UnmanagedType.LP

如果文件名很长,我会尽量确保可以下载该文件。这是我正在使用的类

public class ShortFileName
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetShortPathName(
    [MarshalAs(UnmanagedType.LPTStr)]
    string path,
    [MarshalAs(UnmanagedType.LPTStr)]
    StringBuilder shortPath,
    int shortPathLength
    );
}
这是我的控制器中实现下载的代码

 public ActionResult Download(string path, string fileName)
    {
        try
        {
            StringBuilder shortPath = new StringBuilder(255);

            ShortFileName.GetShortPathName(path, shortPath, shortPath.Capacity);

            byte[] fileBytes = System.IO.File.ReadAllBytes(shortPath.ToString());

            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
        }
        catch (Exception)
        {
            throw;
        }

    }

当文件路径过长时,shortPath为空。

这应该可以工作。如果不需要支持长度超过260个字符的原始路径名,则可以删除所有与
前缀相关的代码

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern uint GetShortPathName(
    [MarshalAs(UnmanagedType.LPTStr)]
    string lpszLongPath,
    [MarshalAs(UnmanagedType.LPTStr)]
    StringBuilder lpszShortPath,
    uint cchBuffer);

public static string ShortFilenameFor(string longFilename)
{
    // Add to the long filename a prefix to cause the API to handle filenames longer than 260 characters.

    const string PREFIX = @"\\?\";
    longFilename = PREFIX + longFilename;

    // First check how much space is required for the short filename.

    uint length = GetShortPathName(longFilename, null, 0);

    if (length == 0)
        throw new Win32Exception(Marshal.GetLastWin32Error());

    // Now allocate buffer of the correct length and fill it.

    StringBuilder buffer = new StringBuilder((int)length);
    uint result = GetShortPathName(longFilename, buffer, length);

    if (result == 0)
        throw new Win32Exception(Marshal.GetLastWin32Error());

    buffer.Remove(0, PREFIX.Length);
    return buffer.ToString();
}

您是否可以更新您的问题以显示“文件路径过长”的含义,然后您希望短路径的预期结果是什么?在260处定义了
MAX\u path
常量,因此您应该使用
StringBuilder(260)
。不清楚为什么您是
GetShortPathName()
。。。您可以在
DllImport
中设置
SetLastError=true
以获取描述问题的异常。是否需要支持长度超过260个字符的文件路径?请注意:Windows 10现在有一个注册表项,您可以在其中选择长文件路径/删除260个最大路径约束
字节[]fileBytes=System.IO.File.ReadAllBytes(shortPath.ToString());返回文件(fileBytes,…
)-除非你有很好的理由,否则不要这样做。将该文件作为流返回。想想如果你有一个大文件要下载会发生什么。