C#中相当于Python的os.path库的是什么?
假设我有一个用C#写的程序,路径是 /a/b/c/xyz.exe,它需要在同一个文件夹里找到 /a/b/c/hello.txt。那我该怎么获取 /a/b/c/hello.txt 的完整路径呢?
在Python中,我可以用 os.path.abspath(sys.argv[0])
来获取正在运行的程序的路径,然后用 dirname() 来获取文件夹的信息,再用 join() 来拼接出新的完整路径。
import sys
from os.path import *
newName = join(dirname(abspath(sys.arg[0]), "hello.txt")
那C#要怎么做同样的事情呢?
2 个回答
1
使用 Application.StartupPath
查看: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath(v=vs.71).aspx
如果程序启动后当前目录发生了变化,那么获取当前目录的操作会失败。
5
你可以使用 Environment.CurrentDirectory、Environment.GetCommandLineArgs 以及 System.IO.Path 里的类来做同样的事情。你的代码可以写成:
// using System.IO;
string newPath = Path.Combine(
Path.GetDirectoryName(
Path.GetFullPath(Environment.GetCommandLineArgs[0])
), "hello.txt");
不过,如果在你调用这个之前,当前目录已经改变了,那就会出错。(在Python中也是这样……)所以,使用下面的方式可能会更好:
// using System.IO;
// using System.Reflection;
string newPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
, "hello.txt");