Home > Software design >  how to get file location from user side in c# console application. I want full path from user side l
how to get file location from user side in c# console application. I want full path from user side l

Time:12-24

I am using this to get file location from user side but user give the full path but I got only File name not a full path.

    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);
           }
        }
   }

which are change required for my code to get the full path.

CodePudding user response:

To get the full path of the process running, you can use

var fullPath = Environment.CurrentDirectory;

CodePudding user response:

GetDirectoryName ist tricky. It always removed the last section.

userInput = "C:\temp\CrossReferencedContent.txt"
Path.GetDirectoryName(userInput):
Result: "C:\temp"

userInput = "C:\temp"
Path.GetDirectoryName(userInput):
Result: "C:\"

userInput = "C:\temp\"
Path.GetDirectoryName(userInput):
Result: "C:\temp"

To get the correct output make sure the path ends with a \ or a filename.

Update based on your comment:

You can use File.Exists(v) to validate the Path.

  • Related