Windows application data path

Application.dataPath

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

Contains the path to the game data folder on the target device (Read Only).

The value depends on which platform you are running on:

Unity Editor: /Assets

Mac player: /Contents

iOS player: / /Data (this folder is read only, use Application.persistentDataPath to save data).

Win/Linux player: (note that most Linux installations will be case-sensitive!)

WebGL: The absolute url to the player data file folder (without the actual data file name)

Android: Normally it points directly to the APK. If you are running a split binary build, it points to the OBB instead.

Windows Store Apps: The absolute path to the player data folder (this folder is read only, use Application.persistentDataPath to save data)

Note that the string returned on a PC will use a forward slash as a folder separator.

For any unlisted platform, run the example script on the target platform to find the dataPath location in the debug log.

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright © 2020 Unity Technologies. Publication Date: 2021-04-11.

Application. User App Data Path Свойство

Определение

Получает путь для данных приложения пользователя. Gets the path for the application data of a user.

Значение свойства

Путь для данных приложения пользователя. The path for the application data of a user.

Примеры

В следующем примере кода показаны две формы и выход из приложения при закрытии обеих форм. The following code example displays two forms and exits the application when both forms are closed. Когда приложение запускается и завершает работу, сохраняется расположение каждой формы. When the application starts and exits, the position of each form is remembered. В этом примере демонстрируется использование UserAppDataPath свойства для хранения данных приложения для пользователя. This example demonstrates using the UserAppDataPath property to store application data for the user.

Класс MyApplicationContext наследует от ApplicationContext и отслеживает, когда закрывается каждая форма, и завершает текущий поток, когда они оба. The class MyApplicationContext inherits from ApplicationContext and keeps track when each form is closed, and exits the current thread when they both are. Класс хранит позиции каждой формы для пользователя. The class stores the positions of each form for the user. Данные о положении формы хранятся в файле Appdata.txt , созданном в расположении, определенном параметром UserAppDataPath . The form position data is stored in a file titled Appdata.txt that is created in the location determined by UserAppDataPath. Main Метод вызывает, Application.Run(context) чтобы запустить приложение, используя ApplicationContext . The Main method calls Application.Run(context) to start the application given the ApplicationContext.

Читайте также:  Мастер настройки беспроводной сети windows

Этот код является выдержкой из примера, показанного в ApplicationContext обзоре класса. This code is an excerpt from the example shown in the ApplicationContext class overview. Для краткости не указан некоторый код. Some code is not shown for the purpose of brevity. ApplicationContextПолный листинг кода см. в разделе. See ApplicationContext for the whole code listing.

Комментарии

Если путь не существует, он создается в следующем формате: If a path does not exist, one is created in the following format:

Данные, хранящиеся в этом пути, являются частью профиля пользователя, включенного для роуминга. Data stored in this path is part of user profile that is enabled for roaming. Перемещаемый пользователь работает на нескольких компьютерах в сети. A roaming user works on more than one computer in a network. Профиль пользователя для перемещаемого пользователя хранится на сервере в сети и загружается в систему при входе пользователя. The user profile for a roaming user is kept on a server on the network and is loaded onto a system when the user logs on. Чтобы профиль пользователя считался перемещаемым, операционная система должна поддерживать перемещаемые профили и должна быть включена. For a user profile to be considered for roaming, the operating system must support roaming profiles and it must be enabled.

Типичным базовым путем является C:\Documents и Settings \ username\Application Data. A typical base path is C:\Documents and Settings\username\Application Data. Однако этот путь будет отличаться, если приложение Windows Forms развертывается с помощью ClickOnce. This path will be different, however, if the Windows Forms application is deployed by using ClickOnce. ClickOnce создает собственный каталог данных приложений, изолированный от всех других приложений. ClickOnce creates its own application data directory that is isolated from all other applications. Дополнительные сведения см. в разделе доступ к локальным и удаленным данным в приложениях ClickOnce. For more information, see Accessing Local and Remote Data in ClickOnce Applications.

Application. Local User App Data Path Свойство

Определение

Получает путь для данных приложения локального неперемещающегося пользователя. Gets the path for the application data of a local, non-roaming user.

Значение свойства

Путь для данных приложения локального неперемещающегося пользователя. The path for the application data of a local, non-roaming user.

Примеры

В следующем примере кода показаны две формы и выход из приложения при закрытии обеих форм. The following code example displays two forms and exits the application when both forms are closed. Когда приложение запускается и завершает работу, сохраняется расположение каждой формы. When the application starts and exits, the position of each form is remembered. Хотя в этом примере демонстрируется использование UserAppDataPath свойства для хранения данных приложения для пользователя, LocalUserAppDataPath вместо него можно использовать. Although this example demonstrates using the UserAppDataPath property to store application data for the user, the LocalUserAppDataPath can be used instead.

Читайте также:  Вывести список всех пользователей windows

MyApplicationContext Класс наследует от ApplicationContext и отслеживает, когда закрывается каждая форма, и завершает текущий поток, когда они оба. The MyApplicationContext class inherits from ApplicationContext and keeps track when each form is closed, and exits the current thread when they both are. Класс хранит позиции каждой формы для пользователя. The class stores the positions of each form for the user. Данные о положении формы хранятся в файле Appdata.txt , созданном в расположении, определенном параметром UserAppDataPath . The form position data is stored in a file titled Appdata.txt that is created in the location determined by UserAppDataPath. Main Метод вызывает, Application.Run(context) чтобы запустить приложение, используя ApplicationContext . The Main method calls Application.Run(context) to start the application given the ApplicationContext.

Этот код является выдержкой из примера, показанного в ApplicationContext обзоре класса. This code is an excerpt from the example shown in the ApplicationContext class overview. Для краткости не указан некоторый код. Some code is not shown for the purpose of brevity. ApplicationContextПолный листинг кода см. в разделе. See ApplicationContext for the whole code listing.

Комментарии

Локальный пользователь — это тот, чей профиль пользователя хранится в системе, в которой пользователь вошел в систему. A local user is one whose user profile is stored on the system on which the user logged on. Если путь не существует, он создается в следующем формате: If a path does not exist, one is created in the following format:

Типичным базовым путем является C:\Documents и Settings \ username\Local Settings\Application Data. A typical base path is C:\Documents and Settings\username\Local Settings\Application Data. Однако этот путь будет отличаться, если приложение Windows Forms развертывается с помощью ClickOnce. This path will be different, however, if the Windows Forms application is deployed by using ClickOnce. ClickOnce создает собственный каталог данных приложений, изолированный от всех других приложений. ClickOnce creates its own application data directory that is isolated from all other applications. Дополнительные сведения см. в разделе доступ к локальным и удаленным данным в приложениях ClickOnce. For more information, see Accessing Local and Remote Data in ClickOnce Applications.

Application. Local User App Data Path Property

Definition

Gets the path for the application data of a local, non-roaming user.

Property Value

The path for the application data of a local, non-roaming user.

Examples

The following code example displays two forms and exits the application when both forms are closed. When the application starts and exits, the position of each form is remembered. Although this example demonstrates using the UserAppDataPath property to store application data for the user, the LocalUserAppDataPath can be used instead.

Читайте также:  Что за клавиша option mac os

The MyApplicationContext class inherits from ApplicationContext and keeps track when each form is closed, and exits the current thread when they both are. The class stores the positions of each form for the user. The form position data is stored in a file titled Appdata.txt that is created in the location determined by UserAppDataPath. The Main method calls Application.Run(context) to start the application given the ApplicationContext.

This code is an excerpt from the example shown in the ApplicationContext class overview. Some code is not shown for the purpose of brevity. See ApplicationContext for the whole code listing.

Remarks

A local user is one whose user profile is stored on the system on which the user logged on. If a path does not exist, one is created in the following format:

A typical base path is C:\Documents and Settings\username\Local Settings\Application Data. This path will be different, however, if the Windows Forms application is deployed by using ClickOnce. ClickOnce creates its own application data directory that is isolated from all other applications. For more information, see Accessing Local and Remote Data in ClickOnce Applications.

Location of Application.persistentDataPath in a build

When I run my game from the editor and save load data, I find that data in: C:\Users\User\AppData\LocalLow\DefaultCompany\projectname\data .

When I build it and get an executable, that data still loads fine, but if I save and restart, it does not get saved. However it does when I launch it from the Editor.

Is this a fault in my code or is the files somewhere else when I don’t run it from Unity Editor?

Later when I export the game to launch it, I have persistent data I Json files that have to come with it for the game to work.

For clarity, here is the class that handles save/load of Json:

1 Answer 1

In the answer below:

  • companyname = Company name from the Build Settings
  • productname = Product name from the Build Settings

Windows:

Windows Store:

Mac:

older version of Unity on Mac:

Linux:

which is the-same as

Android:

with SD card on the Android device:

iOS:

Example of the RandomFolderName full name:

On iOS, you will be given access to the app’s sandbox which is the Document folder. You must create folder inside this directory in order to create a new file inside it.

If you have a default data values in a json file, put the file in Assets/Resources folder so that it will be read-only then read it with TextAsset . When the game loads, you can use PlayerPrefs to check if this is the first time the game being loaded.

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