c#获取Windows当前选文件定路径

发布时间 2023-10-30 17:17:54作者: 少年。

在Windows系统中点击文件后获取到文件完整路径

/// <summary>
/// 获取Windows当前选中的文件或文件夹的完整路径
/// </summary>
/// <returns>完整路径</returns>
private static string GetWindowsSelectedPath()
{  
    // 获取命令行参数
    string[] commandLineArgs = Environment.GetCommandLineArgs();
    // 检查是否有参数传入
    if(commandLineArgs.Length > 1)
    {   
         // 获取传入的路径
        string path = commandLineArgs[1];
         // 检查路径是否存在文件或文件夹
        if(File.Exists(path) || Directory.Exists(path))
        {
            // 返回完整路径
            return path;
        }
    }
    // 如果没有找到有效路径,则返回null
    return null;
}