在c#中以编程方式查找Windows文件夹

时间:2009-09-30 16:47:36

标签: c# windows directory special-folders

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

我尝试在Environment.SpecialFolder下查找。但我没有看到

下的“Windows”选项

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:63)

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

试试这些:

Environment.GetEnvironmentVariable("SystemRoot")

Environment.GetEnvironmentVariable("windir")

答案 1 :(得分:39)

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

答案 2 :(得分:11)

我强烈建议使用:

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

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

答案 3 :(得分:9)

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

该短程序将终止所有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");
}
相关问题