How to get current windows directory e.g. C:\ in C#

后端 未结 4 1186
清歌不尽
清歌不尽 2020-12-31 00:31

As the title suggests, how can you get the current OS drive, so you could add it in a string e.g.:

MessageBox.Show(C:\\ + \"My Documents\");
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 00:49

    When looking for a specific folder (such as My Documents), do not use a hard-coded path. Paths can change from version-to-version of Windows (C:\Documents and Settings\ vs C:\Users\) and were localized in older versions (C:\Users\user\Documents\ vs C:\Usuarios\user\Documentos\). Depending on configuration, user profiles could be on a different drive than Windows. Windows might not be installed where you expect it (it doesn't have to be in \Windows\). There's probably other cases I'm not aware of.

    Instead, use the Shell API (SHGetKnownFolderPath) to get the actual path. In .NET, these values are easily obtained from Environment.GetFolderPath. If you're looking for the user's My Documents folder:

    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    

    Full list of special folders

提交回复
热议问题