获得应用程序的根我目前正在使用:如何获取/设置winforms应用程序的工作目录?
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)
但是那种感觉马虎给我。有没有更好的方式来获取应用程序的根目录并将其设置为工作目录?
获得应用程序的根我目前正在使用:如何获取/设置winforms应用程序的工作目录?
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)
但是那种感觉马虎给我。有没有更好的方式来获取应用程序的根目录并将其设置为工作目录?
所以,你可以只使用Envrionment.CurrentDirectory =(sum目录)更改目录。有很多方法可以获得原始执行的directoy,一种方式实质上就是您所描述的方式,而另一种方式是通过Directory.GetCurrentDirectory()(如果您没有更改目录)。
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Get the current directory.
string path = Directory.GetCurrentDirectory();
string target = @"c:\temp";
Console.WriteLine("The current directory is {0}", path);
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
// Change the current directory.
Environment.CurrentDirectory = (target);
if (path.Equals(Directory.GetCurrentDirectory()))
{
Console.WriteLine("You are in the temp directory.");
}
else
{
Console.WriteLine("You are not in the temp directory.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
你想要什么;工作目录或程序集所在的目录?
对于当前目录,您可以使用Environment.CurrentDirectory
。对于该组件所在的目录,你可以使用这个:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)