How do I get/set a winforms application's working directory?
To get the Application's root I am Currently using:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)开发者_如何学运维
But that feels sloppy to me. Is there a better way to get the root directory of the application and set that to the working directory?
So, you can change directory by just using Envrionment.CurrentDirectory = (sum directory). There are many ways to get the original executing directoy, one way is essentially the way you described and another is through Directory.GetCurrentDirectory() if you have not changed the directory.
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());
}
}
ref
What is it that you want; the working directory, or the directory in which the assembly is located?
For the current directory, you can use Environment.CurrentDirectory
. For the directory in which the assembly is located, you can use this:
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
精彩评论