Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path.GetFullPath returning wrong path in C#

Tags:

c#

wpf

filepath

According to the MSDN docs, to get the full file path of a file use

var fileName = Path.GetFullPath("KeywordsAndPhrases.txt");

Which I would assume delivers the full path of that file for the project it is in.

'K:\HeadlineAutoTrader\Autotrader.Infrastructure.HeadlineFeeds\Data\KeywordsAndPhrases.txt'

Which it doesn't, it returns;

'K:\HeadlineAutoTrader\AutotraderTests\bin\Debug\Data\KeywordsAndPhrases.txt'

which somewhat makes sense as the code I'm testing is being run in the test project.

So the question is how does one get the full filepath of a text file in a folder in another class library within the same solution?

This is a WPF based project, obviously it would be easier in a web app as Server.MapPath works great

like image 299
dinotom Avatar asked Jul 27 '26 17:07

dinotom


2 Answers

When you call File.GetFullPath, the library looks at the current directory for the executing program. Unless otherwise specified, this is the same folder the executable is in.

You likely have "Copy to Output Directory" set to "Copy always" or "Copy if newer" in the properties of the KeywordsAndPhrases.txt file in Visual Studio, meaning it is copied to the same folder as the executable. Otherwise, the file may have been copied there by some other process (e.g. manually, post build step batch file). That is why it finds the file under K:\HeadlineAutoTrader\AutotraderTests\bin\Debug instead of K:\HeadlineAutoTrader\Autotrader.Infrastructure.HeadlineFeeds.

How does one get the full filepath of a text file in a folder in another class library within the same solution?

The question does not make sense. Executables do not know about class libraries or the structure of files within a Visual Studio project. Executables know about either resources embedded in assemblies or files in folders. If you want to find the full path of a particular file, either set the current directory to that folder using Environment.CurrentDirectory or use a known relative path.

like image 76
akton Avatar answered Jul 29 '26 07:07

akton


From https://msdn.microsoft.com/en-us/library/system.io.path.getfullpath%28v=vs.110%29.aspx

This method uses current directory and current volume information to fully qualify path. If you specify a file name only in path, GetFullPath returns the fully qualified path of the current directory.

You can investigate the current working directory by using Environment.CurrentDirectory.

So the method is behaving as documented.

If you want the path relative to the main executable, take a look at What is the best way to get the executing exe's path in .NET?

like image 43
Nathan Avatar answered Jul 29 '26 08:07

Nathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!