Windows forms application path

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.

Этот код является выдержкой из примера, показанного в 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.StartupPath

app.path = Application.StartupPath
В VB 6.0 была такая фича: пишешь app.path & ‘ amefili.txt’, а как это будет выглядить в .NET?

Обновление приложения: можно ли использовать Application.StartupPath в качестве корневой папки
Привет всем)))) есть несколько вопросов по поводу этой темы Итак первый вопрос: #Region.

Как подняться на один уровень вверх относительно пути «Application.StartupPath»
В папке с установленным приложением1 находится папка «Other» с приложением2. Нужно, чтобы.

Читайте также:  Даунгрейд windows 10 pro до windows 10 home

Пояснение к коду
Добрый день! Вопрос в следующем, есть конструктор объявленный в хелпе: virtual __fastcall.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Пояснение по коду
Плиз хелп с кодом, если не сложно, напишите комментарии к // Add // Remove // Get, не понимаю, что.

пояснение к коду
помогите пожалуйста. напишите поянение к коду. var f1, f2 : text; s : string; i .

Дайте пояснение по коду
int count = 0; for (int i = 0; strok; i++) < if ((strok == 'a' && strok == ';') || (strok ==.

Задача о рюкзаке методом полного перебора. Нужно пояснение по коду
Здравствуйте, нужно пояснение по этому коду. Код не мой, также в нем много ошибок. Заранее спасибо.

Сколько у Пети способов попасть в школу, пройдя ровно K шагов. Пояснение по коду
Есть такая задача: На расстоянии N шагов от школы стоит Петя. Каждую минуту он выбирает, куда.

Application. User App Data Path Property

Definition

Gets the path for the application data of a user.

Property Value

The path for the application data of a 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. This example demonstrates using the UserAppDataPath property to store application data for the user.

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. 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

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.

A typical base path is C:\Documents and Settings\username\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.

How can I save application settings in a Windows Forms application?

What I want to achieve is very simple: I have a Windows Forms (.NET 3.5) application that uses a path for reading information. This path can be modified by the user, by using the options form I provide.

Now, I want to save the path value to a file for later use. This would be one of the many settings saved to this file. This file would sit directly in the application folder.

I understand three options are available:

  • ConfigurationSettings file (appname.exe.config)
  • Registry
  • Custom XML file

I read that the .NET configuration file is not foreseen for saving values back to it. As for the registry, I would like to get as far away from it as possible.

Does this mean that I should use a custom XML file to save configuration settings?

If so, I would like to see code example of that (C#).

I have seen other discussions on this subject, but it is still not clear to me.

14 Answers 14

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn’t exist.

Читайте также:  Установка мой офис астра линукс

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

This technique is applicable both for console, Windows Forms, and other project types.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default. will be read-only.

If you are planning on saving to a file within the same directory as your executable, here’s a nice solution that uses the JSON format:

The registry is a no-go. You’re not sure whether the user which uses your application, has sufficient rights to write to the registry.

You can use the app.config file to save application-level settings (that are the same for each user who uses your application).

I would store user-specific settings in an XML file, which would be saved in Isolated Storage or in the SpecialFolder.ApplicationData directory.

Next to that, as from .NET 2.0, it is possible to store values back to the app.config file.

The ApplicationSettings class doesn’t support saving settings to the app.config file. That’s very much by design; applications that run with a properly secured user account (think Vista UAC) do not have write access to the program’s installation folder.

You can fight the system with the ConfigurationManager class. But the trivial workaround is to go into the Settings designer and change the setting’s scope to User. If that causes hardships (say, the setting is relevant to every user), you should put your Options feature in a separate program so you can ask for the privilege elevation prompt. Or forego using a setting.

The registry/configurationSettings/XML argument still seems very active. I’ve used them all, as the technology has progressed, but my favourite is based on Threed’s system combined with Isolated Storage.

The following sample allows storage of an objects named properties to a file in isolated storage. Such as:

Properties may be recovered using:

It is just a sample, not suggestive of best practices.

I wanted to share a library I’ve built for this. It’s a tiny library, but a big improvement (IMHO) over .settings files.

The library is called Jot (GitHub). Here is an old The Code Project article I wrote about it.

Here’s how you’d use it to keep track of a window’s size and location:

The benefit compared to .settings files: There’s considerably less code, and it’s a lot less error-prone since you only need to mention each property once.

With a settings files you need to mention each property five times: once when you explicitly create the property and an additional four times in the code that copies the values back and forth.

Storage, serialization, etc. are completely configurable. When the target objects are created by an IoC container, you can [hook it up][] so that it applies tracking automatically to all objects it resolves, so that all you need to do to make a property persistent is slap a [Trackable] attribute on it.

It’s highly configurable, and you can configure: — when data is persisted and applied globally or for each tracked object — how it’s serialized — where it’s stored (e.g. file, database, online, isolated storage, registry) — rules that can cancel applying/persisting data for a property

Trust me, the library is top notch!

A simple way is to use a configuration data object, save it as an XML file with the name of the application in the local Folder and on startup read it back.

Here is an example to store the position and size of a form.

Читайте также:  Служба установщик windows была запущена

The configuration dataobject is strongly typed and easy to use:

A manager class for saving and loading:

Now you can create an instance and use in your form’s load and close events:

And the produced XML file is also readable:

I don’t like the proposed solution of using web.config or app.config . Try reading your own XML. Have a look at XML Settings Files – No more web.config.

Other options, instead of using a custom XML file, we can use a more user friendly file format: JSON or YAML file.

  • If you use .NET 4.0 dynamic, this library is really easy to use (serialize, deserialize, nested objects support and ordering output as you wish + merging multiple settings to one) JsonConfig (usage is equivalent to ApplicationSettingsBase)
  • For .NET YAML configuration library. I haven’t found one that is as easy to use as JsonConfig

You can store your settings file in multiple special folders (for all users and per user) as listed here Environment.SpecialFolder Enumeration and multiple files (default read only, per role, per user, etc.)

If you choose to use multiple settings, you can merge those settings: For example, merging settings for default + BasicUser + AdminUser. You can use your own rules: the last one overrides the value, etc.

«Does this mean that I should use a custom XML file to save configuration settings?» No, not necessarily. We use SharpConfig for such operations.

For instance, if a configuration file is like that

We can retrieve values like this

It is compatible with .NET 2.0 and higher. We can create configuration files on the fly and we can save it later.

As far as I can tell, .NET does support persisting settings using the built-in application settings facility:

The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving. — http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx

Yes, it is possible to save the configuration — but it pretty much depends on the way you choose to do it. Let me describe the technical differences so you can understand the options you have:

First, you need to distinguish, whether you want to use applicationSettings or AppSettings in your *.exe.config (aka App.config in Visual Studio) file — there are fundamental differences, being described here.

Both provide different ways of saving changes:

    The AppSettings allow you to read and write directly into the config file (via config.Save(ConfigurationSaveMode.Modified); , where config is defined as config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ).

  • The applicationSettings allow to read, but if you write changes (via Properties.Settings.Default.Save(); ) it will be written on a per-user basis, stored in a special place (e.g. C:\Documents and Settings\USERID\Local Settings\Application Data\FIRMNAME\WindowsFormsTestApplicati_Url_tdq2oylz33rzq00sxhvxucu5edw2oghw\1.0.0.0 ). As Hans Passant mentioned in his answer, this is because a user usually has restricted rights to Program Files and cannot write to it without invoking the UAC prompt. A disadvantage is if you’re adding configuration keys in the future you need to synchronize them with every user profile.
  • Note: As mentioned in the question, there is a 3rd option: If you treat the configuration file as XML document, you can load, modify and save it by using the System.Xml.Linq.XDocument class. It is not required to use a custom XML file, you can read the existing config file; for querying elements, you can even use Linq queries. I have given an example here, check out the function GetApplicationSetting there in the answer.

    If you require encryption to protect your values, check out this answer.

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