You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#控制台程序中获取用户提供的完整文件路径

问题描述

我尝试使用以下代码从用户端获取文件位置,但当用户输入完整路径(如C:\Filepath)时,只能得到文件名而非完整路径。请问需要对代码做哪些修改才能获取完整路径?

using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleForChecking
{
   internal class Program
   {
       static void Main(string[])
       {
           Console.WriteLine("Enter file name:");
           string v = Console.ReadLine();
           var applicationPath = Path.GetDirectoryName(v);
           Console.WriteLine(applicationPath);
       }
    }
}
解决方案

你的代码存在两个核心问题:

  • Path.GetDirectoryName()的作用是提取路径中的目录部分,而非返回完整路径。比如输入C:\File\test.txt,它会返回C:\File;输入根目录下的C:\Filepath,它会返回C:\,完全不符合你获取完整路径的需求。
  • Main方法的参数声明错误,正确写法应为static void Main(string[] args)。

要实现获取完整路径的需求,可根据场景选择以下两种修改方式:

方式1:自动转换为绝对完整路径(支持相对/绝对输入)

使用Path.GetFullPath()方法,它会将用户输入的相对路径自动转换为绝对路径,若输入本身是绝对路径则直接返回:

using System.IO;
namespace ExampleForChecking
{
   internal class Program
   {
       static void Main(string[] args)
       {
           Console.WriteLine("Enter file path:");
           string inputPath = Console.ReadLine();
           string fullPath = Path.GetFullPath(inputPath);
           Console.WriteLine("完整路径:" + fullPath);
       }
    }
}

方式2:仅校验并返回合法绝对路径

如果只接受用户输入绝对路径,可直接输出输入内容并添加合法性校验:

using System.IO;
namespace ExampleForChecking
{
   internal class Program
   {
       static void Main(string[] args)
       {
           Console.WriteLine("Enter absolute file path:");
           string inputPath = Console.ReadLine();
           
           if (Path.IsPathRooted(inputPath))
           {
               Console.WriteLine("完整路径:" + inputPath);
           }
           else
           {
               Console.WriteLine("请输入合法的绝对路径!");
           }
       }
    }
}

内容的提问来源于stack exchange,提问作者Sanjeev singh kushvaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:30:22