【问题标题】:What is the most secure way to retrieve the system Drive检索系统驱动器的最安全方法是什么
【发布时间】:2010-10-28 22:37:08
【问题描述】:

我知道以下应该有效:

Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) 

我对这个调用的问题是,如果由于某种原因有人决定删除“windir”Env Var,这将不起作用。

有没有更安全的方法来获取系统驱动器?

【问题讨论】:

    标签: c# .net windows environment-variables system-administration


    【解决方案1】:
    string windir = Environment.SystemDirectory; // C:\windows\system32
    string windrive = Path.GetPathRoot(Environment.SystemDirectory); // C:\
    

    注意:此属性在内部使用 GetSystemDirectory() Win32 API。它不依赖于环境变量。

    【讨论】:

      【解决方案2】:

      这个返回系统目录(system32)的路径。

      Environment.GetFolderPath(Environment.SpecialFolder.System)
      

      你也许可以使用它,那么你就不需要依赖环境变量了。

      【讨论】:

      • 值得注意的是,GetFolderPath 让您担心环境变量,因为它在内部使用 SHGetFolderPath。
      【解决方案3】:

      我实际上可能误解的一件事是您想要系统驱动器,但是通过使用“windir”,您将获得 windows 文件夹。因此,如果您需要一种安全方式来获取 windows 文件夹,您应该使用良好的旧 API 函数 GetWindowsDirectory。

      这是为 C# 使用准备的函数。 ;-)

          [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
          static extern uint GetWindowsDirectory(StringBuilder lpBuffer, uint uSize);
      
          private string WindowsDirectory()
          {
              uint size = 0;
              size = GetWindowsDirectory(null, size);
      
              StringBuilder sb = new StringBuilder((int)size);
              GetWindowsDirectory(sb, size);
      
              return sb.ToString();
          }
      

      所以如果你真的需要运行 Windows 的驱动器,你可以在之后调用

      System.IO.Path.GetPathRoot(WindowsDirectory());
      

      【讨论】:

      • @Richard:没错,但我并没有仅仅指出具体的方向,而是添加了一个示例,说明如何使用该函数。
      【解决方案4】:

      您可以使用GetWindowsDirectory API 来检索 windows 目录。

      【讨论】:

        【解决方案5】:

        永远不要读取环境变量(任何脚本或用户都可以更改它们!)
        官方方法(MS 内部,Explorer 使用)是几十年来的 Win32 api 常见问题解答(参见 Google 群组、Win32、System api)

        【讨论】:

          【解决方案6】:

          有一个名为SystemDrive的环境变量

          C:\>SET SystemDrive
          SystemDrive=C:
          

          【讨论】:

          • 不幸的是,该方法与原始 WinDir 环境变量存在相同的问题 - 用户可以任意更改或将其从环境中删除。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-12-01
          • 2011-05-16
          • 1970-01-01
          • 1970-01-01
          • 2012-06-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多