Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative path to a file using C#

I have a command-line program that takes a configuration file as a parameter, that is, C:\myprogram.exe -c C:\configFiles\MyConfigFile.txt. I want to be able to make it so that I do not have to type the absolute path to the configuration file, so instead of the above I can just enter C:\myprogram.exe -c MyConfigFile.txt

I'm not familiar enough with how C# deals with paths to understand if or how this can be done. Any insight is appreciated.

like image 974
kingrichard2005 Avatar asked Jan 19 '11 20:01

kingrichard2005


3 Answers

Use Path.GetFullPath()

Something like:

string path = "MyConfigFile.txt";
string fullPath = System.IO.Path.GetFullPath(path);

That's if the config file is in the current directory. If they're stored in a standard folder you can use Path.Combine()

string basePath = "C:\Configs";
string file = "MyConfigFile.txt";
string fullPath = System.IO.Path.Combine(basePath, file);
like image 113
Nemo157 Avatar answered Oct 13 '22 06:10

Nemo157


You are only passing in a string. It is up to you to handle it in a relative path way.

If you used this code, it would by default support relative paths.

FileInfo will attempt to use the path in Environment.CurrentDirectory first, if the path provided is not explicit.

var file = new FileInfo(args[1]); // args[1] can be a filename of a local file
Console.WriteLine(file.FullName); // Would show the full path to the file
like image 35
NerdFury Avatar answered Oct 13 '22 06:10

NerdFury


You have some general options:

  • Store the directory path in the config file (you said you don't want to do this)
  • Have the user enter a relative path (....\MyFile.txt)
  • Programmatically search for files matching the name (very slow and prone to locating multiple files of the same name)
  • Assume the data file is in the executing directory

Any way you slice it, the user must indicate the path to the directory, be it in the config file, entering relative path, or selecting from a list of files with identical names found in different directories.

ANALOGY: You place a textbook in a locker, somewhere in a school. You ask your friend to get the book from "a locker", without hinting as to exactly which locker that may be. You should expect to wait a very long time and end up with 50 similar books. Or, provide a clue as to the hallway, bank of lockers, and/or locker number in which the book may be stored. The vagueness of your clue is directly correlated with the response time and potential for returning multiple possibilities.

like image 38
Mike Christian Avatar answered Oct 13 '22 04:10

Mike Christian