加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:53:20 所属栏目:百科 来源:网络整理
导读:要获取应用程序的根目录,我目前正在使用: Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6) 但这让我觉得草率.有没有更好的方法来获取应用程序的根目录并将其设置为工作目录? 解决方法 因此,您只需使用Envrionmen
要获取应用程序的根目录,我目前正在使用:

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());
        }
    }

ref

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读