gpt4 book ai didi

c# - 如何获取/设置 winforms 应用程序的工作目录?

转载 作者:行者123 更新时间:2023-11-30 13:29:22 24 4
gpt4 key购买 nike

获取我当前使用的应用程序的根目录:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6)

但这对我来说很草率。有没有更好的方法来获取应用程序的根目录并将其设置为工作目录?

最佳答案

因此,您只需使用 Environment.CurrentDirectory = (sum directory) 即可更改目录。有很多方法可以获取原始执行目录,一种方法基本上就是您描述的方式,另一种方法是通过 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());
}
}

ref

关于c# - 如何获取/设置 winforms 应用程序的工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1590097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com