设置Winforms应用程序的工作目录

设置Winforms应用程序的工作目录

本文介绍了如何获取/设置Winforms应用程序的工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取我当前正在使用的应用程序的根目录,

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?

推荐答案

因此,只需使用Envrionment.CurrentDirectory =(总目录)即可更改目录.获取原始执行目录的方法有很多,一种方法实质上是您描述的方法,另一种方法是通过Directory.GetCurrentDirectory()(如果您尚未更改目录).

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

参考

这篇关于如何获取/设置Winforms应用程序的工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:07