Windows get user folder

How to open your user profile folder in Windows

In Windows, your user profile folder is a special folder containing files and folders pertaining only to you. It contains your Desktop, your Documents, and personal data such as your application preferences.

Files in the user profile folder are private to you. If other people use your computer, they cannot view and change the files in your user profile folder, unless they are an administrator. The same permissions apply to all subdirectories of your profile directory, such as your Desktop directory, your Documents directory, etc.

Where is the user profile folder?

Your user profile folder is located in the Users folder on your Windows system drive, which on most computers is C:.

In the Users folder, your profile folder name is the same as your username. If your username is hope, your user profile folder is located at C:\Users\hope\.

The %USERPROFILE% environment variable

If you’re not sure what your username is, you can always get to your profile folder using the environment variable %USERPROFILE%.

An environment variable is a special word containing a value. The %USERPROFILE% variable contains the path of your user profile folder.

Using %USERPROFILE% in File Explorer

In your File Explorer, the location bar shows the name of the folder you’re viewing. It works like an address bar in a web browser. You can type a location on your computer into the location bar, and File Explorer opens that folder.

As shown in the following steps, if you type %USERPROFILE% in the location bar, File Explorer opens your profile folder.

    Open a new File Explorer window. You can open it from the Start menu (Windows SystemFile Explorer).

Or, press the keyboard shortcut Windows key + E (hold down the Windows key and press E).

  • Click in the location bar.
  • Type %USERPROFILE% and press Enter .
    1. File Explorer opens your user profile folder and displays its contents. The title bar of the window and your location bar both display your full login name.

    Using %USERPROFILE% in Command Prompt

    If you use the Windows Command Prompt, you can use the cd command with %USERPROFILE% to change the current directory to your profile folder.

    1. Open the Command Prompt. For example, press Windows key + R to open the run box, then type cmd and press Enter .

    1. Your command prompt displays the current directory, followed by a >.

    By default, when you open a new Command Prompt window, the current directory is your user profile folder.

    1. To change to your profile folder at any time, use the cd command:
    Читайте также:  Видеоплеер для windows 10 тормозит

    1. You can also use the echo command to display the value of %USERPROFILE%.

    To view your username, use echo %USERNAME%.

    For more information about environment variables, see: What are the default environment variables in Windows?

    Why do I need to open the profile folder?

    Usually, you don’t need to open your profile folder directly. The Quick Access shortcuts on the left side of the File Explorer window (Desktop, Documents, Downloads, Music, etc.) already point to the major folders in your profile directory.

    As a general rule, you should not rearrange the files and folders that already exist in your profile directory, because Windows expects them to have certain names and locations. For instance, do not move or rename your Desktop folder.

    However, you can put files and folders in your profile directory if you choose.

    Also, some tasks, such as adding items to your Startup folder, require you know the location of your profile folder.

    Где в ОС Windows 10 находится папка Users и как ее отыскать, инструкция

    Для некоторых настроек и изменений пользователю операционной системы необходим доступ к определенным встроенным блокам. Поэтому важно изучить дополнительную информацию о том, где находится специальная папка «Users» в операционке Windows 10, для чего она нужна и что делать, если указанный элемент пропал. Поэтапное изучение данных позволит корректно использовать документ и правильно указывать требуемые изменения.

    Что это за папка?

    Элемент с названием «Users» (с английского переводится как «Пользователи») – это часть корневого каталога встроенных блоков операционной системы Виндовс.

    • появляется в автоматическом режиме после того, как юзер создал и активировал локальную учетную запись;
    • содержит несколько обязательных компонентов – подпапки с именами «User», «Program Files», «Администратор» и «Общие»;
    • внутри каталога «Администратор» операционной системой персонального компьютера создаются следующие разделы – «AppData», «Printhood», «Cookies», «Рабочий стол», «Загрузки» и «Документы».

    Внимание! С перечисленными папками можно производить разные действия – перенос, копирование, изменение названия. Но с блоком «Program Files» работать в подобном формате недопустимо, это может привести к различным ошибкам и неисправностям.

    Папка «Пользователи» хранит информацию о созданном профиле юзера – история использования браузера, отдельные настройки, которые собственник аккаунта ПК выполняет в процессе работы.

    Где она находится?

    Чтобы проверить информацию, занесенную в папку «Пользователи» («Users»), необходимо правильно найти ее расположение. Элемент с указанным названием автоматически записывается на диск «С», путь – С:\Users. Существует несколько основных способов, с помощью которых можно получить доступ к нужной папке:

    • через поисковую строку (обозначается значком лупы, находится в меню Пуск или рядом с иконкой «Win» на панели быстрого запуска);
    • открыть Проводник, в поле назначений прописать путь к папке, подтвердить операцию клавишей «Enter».

    Прежде чем вносить изменения и осуществлять перенос раздела «Users», необходимо ознакомиться с определенными ограничениями и требованиями:

    • раздел, куда планируется перенести элемент «Пользователи», должен работать через файловый реестр типа NTFS;
    • не следует вносить корректировки и осуществлять перенос, если внутри раздела сохранены данные другой операционной системы;
    • если профиль создан до появления текущей операционной версии, некоторые ссылки могут перестать работать после переноса данных.
    Читайте также:  Не меняются фон рабочего стола windows

    Последний пункт относится к ссылкам, созданным еще до появления вариации типа Виста. В большинстве случаев изменений подобного формата не происходит.

    Куда пропала папка «Users»?

    Иногда юзеры обнаруживают, что необходимый компонент не отображается в разделе. Подобная ситуация – не редкость. Отсутствие папки обозначает, что блок «Пользователи» сохранен как скрытый. Исправить проблему можно самостоятельно, не прибегая к дополнительной помощи мастера. Этапы действий для десятого Виндовса (инструкция подходит для восьмой и седьмой версий):

    • запустить режим работы Проводника (необходимо нажать значок, изображающий папку, или зайти через меню Пуск);

    • выбрать вкладку с названием «Упорядочить»;
    • в выпавшем списке выбрать строку «Параметры папок и поиска»;
    • откроется дополнительное рабочее окно, где следует перейти на вкладку «Вид»;

    • выбрать строку «Показывать скрытые папки и диски», в окошке напротив необходимо поставить отметку активации;

    • кликнуть по кнопке «Применить», «ОК» или «Enter».

    После выполнения указанных инструкций необходимый элемент отобразится в папке, расположенной по пути: «Мой компьютер», «Диск С», «Пользователи», «Имя профиля». Другой способ открытия раздела:

    • открыть встроенный инструмент операционной системы Виндовс «Выполнить» с помощью комбинации горячих клавиш «Win» и «R»;
    • в пустом поле дополнительного рабочего окна следует ввести специальную команду «%appdata%»;
    • подтвердить запрос кнопкой «ОК» или клавишей «Enter».

    Отдельные компоненты операционных систем Виндовс разных версий требуются для сохранения информации о пользовательском аккаунте и выполненных юзером настроек. Некоторые элементы можно удалить или перенести, но важно заблаговременно ознакомиться с основными характеристиками, требованиями и рекомендациями мастеров, чтобы не создать дополнительных неисправностей.

    How can I get the path of a Windows “special folder” for a specific user?

    Inside a service, what is the best way to determine a special folder path (e.g., «My Documents») for a specific user? SHGetFolderPath allows you to pass in a token, so I am assuming there is some way to impersonate the user who’s folder you are interested in.

    Is there a way to do this based just on a username? If not, what is the minimum amount of information you need for the user account? I would rather not have to require the user’s password.

    4 Answers 4

    I would mount the user’s registry hive and look for the path value. Yes, it’s a sub-optimal solution, for all the reasons mentioned (poor forwards compatibility, etc.). However, like many other things in Windows, MS didn’t provide an API way to do what you want to do, so it’s the best option available.

    You can get the SID (not GUID) of the user by using LookupAccountName. You can load the user’s registry hive using LoadUserProfile, but unfortunately this also requires a user token, which is going to require their password. Fortunately, you can manually load the hive using RegLoadKey into an arbitrary location, read the data, and unload it (I think).

    Yes, it’s a pain, and yes, it’s probably going to break in future versions of Windows. Perhaps by that time MS will have provided an API to do it, back-ported it into older versions of Windows, and distributed it automatically through Windows update. but I wouldn’t hold my breath.

    Get the user’s Desktop folder using Windows API?

    I am trying to get the user’s Desktop folder in a C++ application (via a DLL) by using SHGetSpecialFolderPath :

    Читайте также:  Windows server security check

    First I want to return an else case. I return «ERROR» but the compiler warns me that is trying to convert a CHAR to a LPSTR . With that if there, it looks that the DLL might crash if it cannot get the directory for some reason.

    Also from the MSDN documentation, it says «[SHGetSpecialFolderPath is not supported. Instead, use ShGetFolderPath.]», then I navigate to that page and it says «ShGetFolderPath: Deprecated. Gets the path of a folder identified by a CSIDL value.» What am I supposed to use instead?

    1. I want to add an else case where I return a string saying «ERROR»
    2. I want to know if I am using the correct non-deprecated API function that will work to the modern Windows OS as far back as Windows XP.

    EDIT

    Here is the updated code as requested,

    Compiling with MinGW using: g++ «src\dll\main.cpp» -D UNICODE -D _UNICODE -O3 -DNDEBUG -s -shared -o «output\main.dll»

    I need to pass the string from the DLL as UTF-8 using WideCharToMultiByte(CP_UTF8, . ) , but I am not sure how to do that.

    2 Answers 2

    SHGetFolderPath() returns an HRESULT , where 0 is S_OK , but your code is expecting it to return a BOOL like SHGetSpecialFolderPath() does, where 0 is FALSE . So you need to fix that mistake in your code, as it is currently treating a success as if it were a failure instead.

    With that said, you are returning a LPSTR from your function. That is a char* . But you are using TCHAR for your buffer. TCHAR maps to either char or wchar_t depending on whether UNICODE is defined or not. So you need to decide if you want to return a char* unconditionally, or if you want to return a TCHAR* , or both. It makes a big difference, eg:

    Update: most Win32 API functions do not support UTF-8, so if you want the function to return a UTF-8 string, you will have to call the Unicode flavor of the functions, and then use WideCharToMultiByte() to convert the output to UTF-8. But then you have a problem — who allocates and frees the UTF-8 buffer? There are several different ways to handle that:

    use a thread-safe static buffer (but watch out for this gotcha). If you don’t need to worry about multiple threads accessing the function, then drop the __declspec(thread) specifier:

    have the DLL dynamically allocate the buffer using its own memory manager and return it to the caller, and then require the caller to pass the buffer back to the DLL when done using it so it can be freed with the DLL’s memory manager:

    have the DLL dynamically allocate the buffer using a Win32 API memory manager and return it to the caller, and then the caller can deallocate it using the same Win32 API memory manager without having to pass it back to the DLL to free it:

    have the caller pass in its own buffer that the DLL simply fills in. That way, the caller can decide the best way to allocate and free it:

    Оцените статью