在 C# 中以编程方式查找 windows 文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1499354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:11:20  来源:igfitidea点击:

Find windows folder programmatically in c#

c#windowsdirectoryspecial-folders

提问by Crash893

I am writing a program to kill and restart explorer but I don't want to hard code the location because some people install windows in different places (for example I found someone who had it installed in the d:\ drive where the C:\ drive did exist but had nothing installed on it)

我正在编写一个程序来杀死并重新启动资源管理器,但我不想对该位置进行硬编码,因为有些人将 Windows 安装在不同的位置(例如,我发现有人将它安装在 d:\ 驱动器中,其中 C:\驱动器确实存在,但上面没有安装任何东西)

I tried looking under Environment.SpecialFolder. but I don't see a "windows" option under that

我尝试在 Environment.SpecialFolder 下查找。但我没有看到下面的“windows”选项

What is the best way to do this?

做这个的最好方式是什么?

采纳答案by Omar

http://msdn.microsoft.com/en-us/library/77zkk0b6.aspx

http://msdn.microsoft.com/en-us/library/77zkk0b6.aspx

Try these:

试试这些:

Environment.GetEnvironmentVariable("SystemRoot")

Environment.GetEnvironmentVariable("windir")

回答by Dirk Vollmar

To simply kill and restart Windows Explorer you wouldn't need the path to the system folder as this is already included in the PATH environment variable (unless the user messed with it).

要简单地终止并重新启动 Windows 资源管理器,您不需要系统文件夹的路径,因为它已经包含在 PATH 环境变量中(除非用户弄乱了它)。

That short program will kill all explorer.exe instances and then restart explorer.exe:

那个简短的程序将杀死所有 explorer.exe 实例,然后重新启动 explorer.exe:

static void Main(string[] args)
{
    foreach (Process process in Process.GetProcessesByName("explorer"))
    {
        if (!process.HasExited)
        {
            process.Kill();
        }
    }
    Process.Start("explorer.exe");
}

回答by Uri

Environment.GetFolderPath( Environment.SpecialFolder.Windows )will return the path to the Windows folder. Recommend this approach over the environment variable, because using an API that does exactly what we want (.NET 4.0 and above).

Environment.GetFolderPath( Environment.SpecialFolder.Windows )将返回 Windows 文件夹的路径。推荐这种方法而不是环境变量,因为使用的 API 完全符合我们的要求(.NET 4.0 及更高版本)。

回答by Adam Lindsay

I would highly recommend the use of:

我强烈推荐使用:

Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.System))

It does NOT require administrator rights and supports all versions of the .NET framework.

它不需要管理员权限并支持 .NET 框架的所有版本。