如何在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
相关产品推荐
相关产品推荐

