Python os.path libraries are equivalent in C #

Let's say I have binary code in C # ae / a / b / c / xyz.exe code, and it expects /a/b/c/hello.txt in the same directory. How can I get /a/b/c/hello.txt in the full path?

In python, I can get the running program path using os.path.abspath(sys.argv[0]) , and I can get the directory information with dirname (), and I can use join () for the new full path.

 import sys from os.path import * newName = join(dirname(abspath(sys.arg[0]), "hello.txt") 

How can C # do the same?

+4
source share
2 answers

You can use Environment.CurrentDirectory , Environment.GetCommandLineArgs and classes in System.IO.Path to do the same. Your code will look like this:

 // using System.IO; string newPath = Path.Combine( Path.GetDirectoryName( Path.GetFullPath(Environment.GetCommandLineArgs[0]) ), "hello.txt"); 

This, however, will fail if the current directory has changed before you call it. (That would be in python ...) Perhaps it would be better to use the following:

 // using System.IO; // using System.Reflection; string newPath = Path.Combine( Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) , "hello.txt"); 
+5
source

Use Application.StartupPath

See: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath(v=vs.71).aspx

Getting the current directory will crash if it has been changed since the program started.

+1
source

Source: https://habr.com/ru/post/1339416/


All Articles