要获取应用程序的根目录,我目前正在使用:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)
Run Code Online (Sandbox Code Playgroud)
但这让我觉得草率.有没有更好的方法来获取应用程序的根目录并将其设置为工作目录?
因此,您只需使用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());
}
}
Run Code Online (Sandbox Code Playgroud)
你想要的是什么; 工作目录,或程序集所在的目录?
对于当前目录,您可以使用Environment.CurrentDirectory.对于程序集所在的目录,您可以使用:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12912 次 |
| 最近记录: |