Windows forms resource file

About Resource Files

To include resources in your Windows-based application with RC, do the following:

  1. Create individual files for your cursors, icons, bitmaps, dialog boxes, and fonts.
  2. Create a resource-definition script (.rc file) that describes the resources used by your application.
  3. Compile the script with RC. For more information, see Using RC (The RC Command Line).
  4. Link the compiled resource (.res) file into the application’s executable file with your linker.

A resource file is a text file with the extension .rc. The file can use single-byte, double-byte, or Unicode characters. The syntax and semantics for the RC preprocessor are similar to those of the Microsoft C/C++ compiler. However, RC supports a subset of the preprocessor directives, defines, and pragmas in a script.

The script file defines resources. For a resource that exists in a separate file, such as an icon or cursor, the script specifies the resource and the file that contains it. For some resources, such as a menu, the entire definition of the resource exists within the script.

The following topics describe the information a script file can contain:

  • Comments, which are notes to be ignored by RC.
  • Predefined macros, which take no arguments and cannot be redefined.
  • Preprocessor directives, which instruct RC to perform actions on the script before compiling it.
  • Preprocessor operators, which are used with the #define directive.
  • Pragma directives
  • Resource-definition statements, which name and describe resources.

Файлы ресурсов (C++) Resource Files (C++)

. Так как в проектах на языках программирования .NET не используются файлы описания ресурсов, ресурсы необходимо открывать из обозревателя решений. Since projects in .NET programming languages do not use resource script files, you must open your resources from Solution Explorer. Используйте Редактор изображений и двоичный редактор для работы с файлами ресурсов в управляемых проектах. Use the Image editor and the Binary editor to work with resource files in managed projects.

Все управляемые ресурсы, которые нужно редактировать, должны быть связанными ресурсами. Any managed resources you want to edit must be linked resources. Редакторы ресурсов Visual Studio не поддерживают редактирование внедренных ресурсов. The Visual Studio resource editors do not support editing embedded resources.

Термин файл ресурсов может ссылаться на несколько типов файлов, например: The term resource file can refer to a number of file types, like:

файл описания ресурсов программы (RC); The resource script (.rc) file of a program.

файл шаблона ресурсов (RCT); A resource template (.rct) file.

Отдельный ресурс, существующий как отдельный файл. An individual resource existing as a stand-alone file. Этот тип включает точечный рисунок, значок или файл курсора, на который ссылается RC-файл. This type includes a bitmap, icon, or cursor file that’s referred to from an .rc file.

Файл заголовка, созданный средой разработки. A header file generated by the development environment. Этот тип включает Resource.h , который называется из RC-файла. This type includes Resource.h , that’s referred to from an .rc file.

Ресурсы, найденные в других типах файлов, таких как exe, DLL и RES-файлы, называются ресурсами. Resources found in other file types such as .exe, .dll, and .res files are referred to as resources.

В проекте можно работать с файлами ресурсов и ресурсами . You can work with resource files and resources from within your project. Вы также можете работать с теми, которые не являются частью текущего проекта или были созданы вне среды разработки Visual Studio. You can also work with ones that aren’t part of the current project or were created outside the development environment of Visual Studio. Например, администратор может сделать следующее: For example, you can:

Работать с вложенными и условно включенными файлами ресурсов. Work with nested and conditionally included resource files.

Обновите существующие ресурсы или преобразуйте их в Visual C++. Update existing resources or convert them to Visual C++.

Импортировать графические ресурсы в текущий файл ресурсов или экспортировать их из него. Import or export graphic resources to or from your current resource file.

Включать общие или доступные только для чтения идентификаторы (символы), которые нельзя изменить с помощью среды разработки. Include shared or read-only identifiers (symbols) that can’t be modified by the development environment.

Включите ресурсы в исполняемый файл (exe), который не нуждается в редактировании (или не следует изменять), например общие ресурсы между несколькими проектами. Include resources in your executable (.exe) file that don’t need editing (or shouldn’t be edited), such as shared resources between several projects.

Включать типы ресурсов, не поддерживаемые средой разработки. Include resource types not supported by the development environment.

Изменяемые ресурсы Editable Resources

Чтобы изменить содержащиеся в них ресурсы, можно открыть следующие типы файлов: The following types of files can be opened to edit the resources they contain:

Имя файла File name Описание Description
.rc .rc Файлы скриптов ресурсов Resource script files
.rct .rct Файлы шаблонов ресурсов Resource template files
RES .res Файлы ресурсов Resource files
.resx .resx Управляемые файлы ресурсов Managed resource files
EXE .exe Исполняемые файлы Executable files
DLL .dll Файлы библиотек динамической компоновки Dynamic-link library files
. bmp,. ico,. DIB,. cur .bmp, .ico, .dib, .cur Точечные рисунки, значки, панели инструментов и файлы курсоров Bitmap, icon, toolbar, and cursor files

При редактировании ресурсов среда Visual Studio работает с и влияет на следующие файлы: When editing resources, the Visual Studio environment works with and affects the following files:

Имя файла File name Описание Description
Resource.h Resource.h Файл заголовка, созданный средой разработки, которая содержит определения символов. Header file generated by the development environment that contains symbol definitions.

Включить этот файл в систему управления версиями. Include this file in source control.

Filename.aps Filename.aps Двоичная версия текущего файла скрипта ресурсов, используемая для быстрой загрузки. Binary version of the current resource script file used for quick loading.

Редакторы ресурсов не читают файлы RC или resource. h напрямую. Resource editors don’t directly read .rc or resource.h files. Компилятор ресурсов компилирует их в APS файлы, используемые редакторами ресурсов. The resource compiler compiles them into .aps files that are consumed by the resource editors. Этот файл представляет собой этап компиляции и содержит только символьные данные. This file is a compile step and only stores symbolic data.

Как и в случае обычного процесса компиляции, сведения, не являющиеся символьными, например комментарии, удаляются во время компиляции. As with a normal compile process, information that isn’t symbolic, such as commenting, is discarded during the compile process.

Если файл APS не синхронизирован с RC-файлом, RC-файл создается повторно. Whenever the .aps file is out of synch with the .rc file, the .rc file is regenerated. Например, при сохранении редактор ресурсов перезаписывает файл. RC и файл Resource. h. For example, when you Save, the resource editor overwrites the .rc file and the resource.h file. Любые изменения в ресурсах остаются включенными в RC-файл, но при перезаписании RC-файла комментарии всегда будут потеряны. Any changes to the resources themselves remain incorporated in the .rc file, but comments will always be lost once the .rc file is overwritten. Сведения о том, как сохранять комментарии, см. в разделе Включение ресурсов во время компиляции. For information on how to preserve comments, see Include Resources at Compile Time.

Как правило, файл APS не должен включаться в систему управления версиями. Typically, you shouldn’t include the .aps file in source control.

.rc .rc Файл описания ресурсов, содержащий скрипт для ресурсов в текущем проекте. Resource script file that contains script for the resources in your current project. Этот файл перезаписывается APS-файлом при каждом сохранении. This file is overwritten by the .aps file whenever you save.

Включить этот файл в систему управления версиями. Include this file in source control.

Ресурсы манифеста Manifest Resources

В проектах классических приложений C++ Ресурсы манифеста представляют собой XML-файлы, описывающие зависимости, используемые приложением. In C++ desktop projects, manifest resources are XML files that describe the dependencies an application uses. Например, в Visual Studio созданный мастером MFC файл манифеста определяет, какую версию библиотек DLL общих элементов управления Windows должно использовать приложение: For example, in Visual Studio this MFC wizard-generated manifest file defines which version of the Windows common control DLLs the application should use:

Для приложения Windows XP или Windows Vista ресурс манифеста должен указывать последнюю версию стандартных элементов управления Windows для использования приложением. For a Windows XP or Windows Vista application, the manifest resource should specify the most current version of the Windows common controls for the application to use. В приведенном выше примере используется версия 6.0.0.0 , которая поддерживает элемент управления Syslink. The example above uses version 6.0.0.0 , which supports the Syslink control.

Допускается иметь только один ресурс манифеста на каждый модуль. You can only have one manifest resource per module.

Чтобы просмотреть сведения о версии и типе, содержащиеся в ресурсе манифеста, откройте файл в средстве просмотра XML-данных или в текстовом редакторе Visual Studio. To view the version and type information contained in a manifest resource, open the file in an XML viewer or the Visual Studio text editor. Если вы откроете ресурс манифеста из представления ресурсов, этот ресурс откроется в двоичном формате. If you open a manifest resource from Resource View, the resource will open in binary format.

Открытие ресурса манифеста To open a manifest resource

Откройте проект в Visual Studio и перейдите к Обозреватель решений. Open your project in Visual Studio and navigate to Solution Explorer.

Разверните папку файлы ресурсов , а затем: Expand the Resource Files folder, then:

Чтобы открыть его в текстовом редакторе, дважды щелкните файл . manifest . To open in the text editor, double-click the .manifest file.

Чтобы открыть в другом редакторе, щелкните правой кнопкой мыши файл manifest и выберите команду Открыть с помощью. To open in another editor, right-click the .manifest file and select Open With. Укажите используемый редактор и нажмите кнопку Открыть. Specify the editor to use and select Open.

Создание файлов ресурсов для приложений .NET Create resource files for .NET apps

Ресурсы, такие как строки, изображения или данные объектов, можно включать в файлы ресурсов, чтобы сделать их легко доступными для приложения. You can include resources, such as strings, images, or object data, in resources files to make them easily available to your application. В платформе .NET Framework предлагается пять способов создания файлов ресурсов. The .NET Framework offers five ways to create resources files:

Создайте текстовый файл, содержащий строковые ресурсы. Create a text file that contains string resources. Для преобразования текстового файла в двоичный файл ресурсов (RESOURCES-файл) можно использовать генератор файлов ресурсов (Resgen.exe). You can use Resource File Generator (Resgen.exe) to convert the text file into a binary resource (.resources) file. Затем можно внедрить двоичный файл ресурсов в исполняемый файл приложения или библиотеку приложения с помощью компилятора языка или во вспомогательную сборку с помощью компоновщика сборок (Al.exe). You can then embed the binary resource file in an application executable or an application library by using a language compiler, or you can embed it in a satellite assembly by using Assembly Linker (Al.exe). Дополнительные сведения см. в разделе Ресурсы в текстовых файлах. For more information, see the Resources in Text Files section.

Создайте XML-файл ресурсов (RESX-файл), который содержит строки, изображения или данные объектов. Create an XML resource (.resx) file that contains string, image, or object data. Для преобразования RESX-файла в двоичный файл ресурсов (RESOURCES-файл) можно использовать генератор файлов ресурсов (Resgen.exe). You can use Resource File Generator (Resgen.exe) to convert the .resx file into a binary resource (.resources) file. Затем двоичный файл ресурсов можно внедрить в исполняемый файл приложения или библиотеку приложения с помощью компилятора языка или во вспомогательную сборку с помощью компоновщика сборок (Al.exe). You can then embed the binary resource file in an application executable or an application library by using a language compiler, or you can embed it in a satellite assembly by using Assembly Linker (Al.exe). Дополнительные сведения см. в разделе Ресурсы в RESX-файлах. For more information, see the Resources in .resx Files section.

Создайте XML-файл ресурсов (RESX-файл) программным способом с помощью типов в пространстве имен System.Resources. Create an XML resource (.resx) file programmatically by using types in the System.Resources namespace. Можно создать RESX-файл, перечислить его ресурсы и извлечь конкретные ресурсы по имени. You can create a .resx file, enumerate its resources, and retrieve specific resources by name. Дополнительные сведения см. в разделе Работа с RESX-файлами программным способом. For more information, see Working with .resx Files Programmatically.

Создайте двоичный файл ресурсов (RESOURCES-файл) программным способом. Create a binary resource (.resources) file programmatically. Затем этот файл можно внедрить в исполняемый файл приложения или библиотеку приложения с помощью компилятора языка или во вспомогательную сборку с помощью компоновщика сборок (Al.exe). You can then embed the file in an application executable or an application library by using a language compiler, or you can embed it in a satellite assembly by using Assembly Linker (Al.exe). Дополнительные сведения см. в разделе Ресурсы в RESOURCES-файлах. For more information, see the Resources in .resources Files section.

Создайте файл ресурсов в Visual Studio и включите этот файл в проект. Use Visual Studio to create a resource file and include it in your project. В Visual Studio есть редактор ресурсов,с помощью которого можно добавлять, удалять и изменять ресурсы. Visual Studio provides a resource editor that lets you add, delete, and modify resources. Во время компиляции файл ресурсов автоматически преобразуется в двоичный RESOURCES-файл и внедряется в сборку приложения или вспомогательную сборку. At compile time, the resource file is automatically converted to a binary .resources file and embedded in an application assembly or satellite assembly. Дополнительные сведения см. в разделе Файлы ресурсов в Visual Studio. For more information, see the Resource Files in Visual Studio section.

Ресурсы в формате текстовых файлов Resources in text files

В текстовых файлах (TXT или RESTEXT) можно сохранять только строковые ресурсы. You can use text (.txt or .restext) files to store string resources only. Для нестроковых ресурсов используйте RESX-файлы или создавайте их программными средствами. For non-string resources, use .resx files or create them programmatically. Текстовые файлы, содержащие строковые ресурсы, имеют следующий формат. Text files that contain string resources have the following format:

Форматы TXT- и RESTEXT-файлов ресурсов идентичны. The resource file format of .txt and .restext files is identical. Расширение файла RESTEX служит для того, чтобы текстовые файлы сразу опознавались как файлы ресурсов на основе текста. The .restext file extension merely serves to make text files immediately identifiable as text-based resource files.

Строковые ресурсы представляются в виде пар имя/значение, где имя — строка, определяющая ресурс, а значение — строка ресурса, которая возвращается при передаче имени методу извлечения ресурсов, например, ResourceManager.GetString. String resources appear as name/value pairs, where name is a string that identifies the resource, and value is the resource string that is returned when you pass name to a resource retrieval method such as ResourceManager.GetString. Имя и значение должны быть разделены знаком равенства (=). name and value must be separated by an equal sign (=). Пример: For example:

Не следует использовать файлы ресурсов для хранения паролей, конфиденциальной информации или личных данных. Do not use resource files to store passwords, security-sensitive information, or private data.

В текстовых файлах допускаются пустые строки (то есть, ресурсы, значение которых равно String.Empty). Empty strings (that is, a resource whose value is String.Empty) are permitted in text files. Пример: For example:

Начиная с .NET Framework 4.5 и во всех версиях .NET Core текстовые файлы поддерживают условную компиляцию с конструкциями #ifdef символ. #endif и #if ! символ. #endif . Starting with .NET Framework 4.5 and in all versions of .NET Core, text files support conditional compilation with the #ifdef symbol. #endif and #if ! symbol. #endif constructs. Для определения символов можно использовать генератор файлов ресурсов (Resgen.exe) с параметром /define . You can then use the /define switch with Resource File Generator (Resgen.exe) to define symbols. Каждый ресурс должен иметь собственную конструкцию #ifdef символ. #endif или #if ! символ. #endif . Each resource requires its own #ifdef symbol. #endif or #if ! symbol. #endif construct. Если при использовании оператора #ifdef указан символ, связанный ресурс добавляется в RESOURCES-файл; в противном случае он не добавляется. If you use an #ifdef statement and symbol is defined, the associated resource is included in the .resources file; otherwise, it is not included. Если при использовании оператора #if ! символ не указан, связанный ресурс добавляется в RESOURCES-файл; в противном случае он не добавляется. If you use an #if ! statement and symbol is not defined, the associated resource is included in the .resources file; otherwise, it is not included.

Комментарии в текстовых файлах необязательны и начинаются с точки с запятой (;) или знака решетки (#) в начале строки. Comments are optional in text files and are preceded either by a semicolon (;) or by a pound sign (#) at the beginning of a line. Строки с комментариями могут находиться в любом месте файла. Lines that contain comments can be placed anywhere in the file. Комментарии не включаются в скомпилированный RESOURCES-файл, созданный с помощью генератора файлов ресурсов (Resgen.exe). Comments are not included in a compiled .resources file that is created by using Resource File Generator (Resgen.exe).

Любые пустые строки в текстовых файлах считаются содержащими пробелы и игнорируются. Any blank lines in the text files are considered to be white space and are ignored.

В следующем примере определяются два строковых ресурса с именами OKButton и CancelButton . The following example defines two string resources named OKButton and CancelButton .

Если в текстовом файле содержатся дубликаты имен, генератор файлов ресурсов (Resgen.exe) отображает предупреждение и игнорирует второе имя. If the text file contains duplicate occurrences of name, Resource File Generator (Resgen.exe) displays a warning and ignores the second name.

Значение не может содержать символы новой строки. Но с помощью escape-символов языка С можно указать символы новой строки ( \n ) и табуляции ( \t ). Также можно включить символ обратной косой черты, предварив его escape-символом (например, «\\»). value cannot contain new line characters, but you can use C language-style escape characters such as \n to represent a new line and \t to represent a tab. You can also include a backslash character if it is escaped (for example, «\\»). Также допускаются пустые строки. In addition, an empty string is permitted.

Сохраняйте ресурсы в формате текстового файла с кодировкой UTF-8 или UTF-16 с прямым или обратным порядком байтов. Save resources in text file format by using UTF-8 encoding or UTF-16 encoding in either little-endian or big-endian byte order. Но генератор файлов ресурсов (Resgen.exe), преобразующий TXT-файл в RESOURCES-файл, по умолчанию обрабатывает файлы в кодировке UTF-8. However, Resource File Generator (Resgen.exe), which converts a .txt file to a .resources file, treats files as UTF-8 by default. Если вы хотите, чтобы программа Resgen.exe могла работать с файлом в кодировке UTF-16, необходимо указать метку порядка байтов Юникода (U+FEFF) в начале файла. If you want Resgen.exe to recognize a file that was encoded using UTF-16, you must include a Unicode byte order mark (U+FEFF) at the beginning of the file.

Чтобы внедрить файл ресурсов в текстовом формате в сборку .NET, необходимо преобразовать текстовый файл в двоичный файл ресурсов (RESOURCES) с помощью генератора файлов ресурсов (Resgen.exe). To embed a resource file in text format into a .NET assembly, you must convert the file to a binary resource (.resources) file by using Resource File Generator (Resgen.exe). Затем можно внедрить RESOURCES-файл в сборку .NET с помощью компилятора языка или во вспомогательную сборку с помощью компоновщика сборок (Al.exe). You can then embed the .resources file in a .NET assembly by using a language compiler or embed it in a satellite assembly by using Assembly Linker (Al.exe).

В следующем примере используется файл ресурсов в текстовом формате GreetingResources.txt для простого консольного приложения «Hello World». The following example uses a resource file in text format named GreetingResources.txt for a simple «Hello World» console application. В этом текстовом файле определены две строки — prompt и greeting , которые предлагают пользователю ввести свое имя и отображают приветствие. The text file defines two strings, prompt and greeting , that prompt the user to enter their name and display a greeting.

Текстовый файл преобразуется в RESOURCES-файл с помощью следующей команды: The text file is converted to a .resources file by using the following command:

В следующем примере показан исходный код для консольного приложения, которое получает сообщения из RESOURCES-файла и выводит их на экран. The following example shows the source code for a console application that uses the .resources file to display messages to the user.

Если вы используете Visual Basic и файл с исходным кодом называется Greeting.vb, используйте следующую команду для создания исполняемого файла, содержащего внедренный RESOURCES-файл: If you are using Visual Basic, and the source code file is named Greeting.vb, the following command creates an executable file that includes the embedded .resources file:

Если вы используете C# и файл исходного кода называется Greeting.cs, исполняемый файл, содержащий внедренный RESOURCES-файл, создается с помощью следующей команды: If you are using C#, and the source code file is named Greeting.cs, the following command creates an executable file that includes the embedded .resources file:

Ресурсы в RESX-файлах Resources in .resx files

В отличие от текстовых файлов, в которых могут храниться только строковые ресурсы, в XML-файлах ресурсов (RESX) могут храниться строки, двоичные данные (такие как изображения, значки и аудиоклипы) и программные объекты. Unlike text files, which can only store string resources, XML resource (.resx) files can store strings, binary data such as images, icons, and audio clips, and programmatic objects. RESX-файл содержит стандартный заголовок, который описывает формат записей ресурсов и включает сведения о версии XML, которые используются для анализа данных. A .resx file contains a standard header, which describes the format of the resource entries and specifies the versioning information for the XML that is used to parse the data. За заголовком XML следуют данные в файле ресурсов. The resource file data follows the XML header. Каждый элемент данных состоит из пары «имя-значение», заключенной в тег data . Each data item consists of a name/value pair that is contained in a data tag. Атрибут name этого тега определяет имя ресурса, а вложенный тег value содержит значение ресурса. Its name attribute defines the resource name, and the nested value tag contains the resource value. Для строковых данных тег value содержит строку. For string data, the value tag contains the string.

Например, следующий тег data определяет строковый ресурс с именем prompt и значением «Enter your name:». For example, the following data tag defines a string resource named prompt whose value is «Enter your name:».

Не следует использовать файлы ресурсов для хранения паролей, конфиденциальной информации или личных данных. Do not use resource files to store passwords, security-sensitive information, or private data.

Для объектов ресурсов тег data содержит атрибут type , указывающий тип данных ресурса. For resource objects, the data tag includes a type attribute that indicates the data type of the resource. Для объектов, состоящих из двоичных данных, тег data также включает атрибут mimetype , который указывает тип base64 двоичных данных. For objects that consist of binary data, the data tag also includes a mimetype attribute, which indicates the base64 type of the binary data.

Во всех RESX-файлах для создания и анализа двоичных данных заданного типа используется форматтер двоичной сериализации. All .resx files use a binary serialization formatter to generate and parse the binary data for a specified type. В результате, если формат двоичной сериализации для объекта изменится недопустимым образом, RESX-файл может стать недействительным. As a result, a .resx file can become invalid if the binary serialization format for an object changes in an incompatible way.

В следующем примере показана часть RESX-файла, в которой содержится ресурс Int32 и растровое изображение. The following example shows a portion of a .resx file that includes an Int32 resource and a bitmap image.

Так как RESX-файлы должны представлять собой XML-код с правильным, заранее определенным форматом, с ними не рекомендуется работать вручную, особенно если они содержат нестроковые ресурсы. Because .resx files must consist of well-formed XML in a predefined format, we do not recommend working with .resx files manually, particularly when the .resx files contain resources other than strings. Вместо этого в Visual Studio предусмотрен прозрачный интерфейс для создания RESX-файлов и управления ими. Instead, Visual Studio provides a transparent interface for creating and manipulating .resx files. Дополнительные сведения см. в разделе Файлы ресурсов в Visual Studio. For more information, see the Resource Files in Visual Studio section. Создавать RESX-файлы и управлять ими можно также программно. You can also create and manipulate .resx files programmatically. Дополнительные сведения см. в разделе Работа с RESX-файлами программным способом. For more information, see Working with .resx Files Programmatically.

Ресурсы в RESOURCES-файлах Resources in .resources files

Для программного создания двоичного файла ресурсов (RESOURCES-файла) непосредственно из кода можно использовать класс System.Resources.ResourceWriter. You can use the System.Resources.ResourceWriter class to programmatically create a binary resource (.resources) file directly from code. Для создания RESOURCES-файла из текстового файла или RESX-файла можно также использовать генератор файлов ресурсов (Resgen.exe). You can also use Resource File Generator (Resgen.exe) to create a .resources file from a text file or a .resx file. Помимо строковых данных, RESOURCES-файл может содержать двоичные данные (массивы байтов) и данные объектов. The .resources file can contain binary data (byte arrays) and object data in addition to string data. Для программного создания RESOURCES-файла необходимо выполнить следующие действия. Programmatically creating a .resources file requires the following steps:

Создайте объект ResourceWriter с уникальным именем файла. Create a ResourceWriter object with a unique file name. Это можно сделать, указав имя файла или файловый поток для конструктора класса ResourceWriter. You can do this by specifying either a file name or a file stream to a ResourceWriter class constructor.

Вызовите одну из перегрузок метода ResourceWriter.AddResource для каждого именованного ресурса, который требуется добавить в файл. Call one of the overloads of the ResourceWriter.AddResource method for each named resource to add to the file. Ресурсом может быть строка, объект или коллекция двоичных данных (массив байтов). The resource can be a string, an object, or a collection of binary data (a byte array).

Вызовете метод ResourceWriter.Close, чтобы записать ресурсы в файл и закрыть объект ResourceWriter. Call the ResourceWriter.Close method to write the resources to the file and to close the ResourceWriter object.

Не следует использовать файлы ресурсов для хранения паролей, конфиденциальной информации или личных данных. Do not use resource files to store passwords, security-sensitive information, or private data.

В следующем примере программным способом создается RESOURCES-файл с именем CarResources.resources, в котором хранятся шесть строк, значок и два объекта, определяемые приложением (два объекта Automobile ). The following example programmatically creates a .resources file named CarResources.resources that stores six strings, an icon, and two application-defined objects (two Automobile objects). Класс Automobile , определенный и созданный в этом примере, отмечен атрибутом SerializableAttribute, который позволяет ему сохраняться модулем форматирования при двоичной сериализации. The Automobile class, which is defined and instantiated in the example, is tagged with the SerializableAttribute attribute, which allows it to be persisted by the binary serialization formatter.

После создания RESOURCES-файла его можно внедрить в исполняемый файл среды выполнения или библиотеку, используя параметр /resource компилятора языка, или во вспомогательную сборку с помощью компоновщик сборок (Al.exe). After you create the .resources file, you can embed it in a run-time executable or library by including the language compiler’s /resource switch, or embed it in a satellite assembly by using Assembly Linker (Al.exe).

Файлы ресурсов в Visual Studio Resource files in Visual Studio

При добавлении файла ресурсов в проект Visual Studio среда Visual Studio создает RESX-файл в каталоге проекта. When you add a resource file to your Visual Studio project, Visual Studio creates a .resx file in the project directory. В Visual Studio имеются редакторы ресурсов, позволяющие добавлять строки, изображения и двоичные объекты. Visual Studio provides resource editors that enable you to add strings, images, and binary objects. Так как редакторы предназначены для обработки только статических данных, их нельзя использовать для хранения программных объектов; данные объектов необходимо записывать в RESX- или RESOURCES-файл программным способом. Because the editors are designed to handle static data only, they cannot be used to store programmatic objects; you must write object data to either a .resx file or to a .resources file programmatically. Дополнительные сведения см. в статье Работа с RESX-файлами программным способом и разделе Ресурсы в RESOURCES-файлах. For more information, see Working with .resx Files Programmatically and the Resources in .resources Files section.

При добавлении локализованных ресурсов указывайте для них то же имя корневого файла, что и для основного файла ресурсов. If you’re adding localized resources, give them the same root file name as the main resource file. Также в имени файла необходимо указать язык и региональные параметры. You should also designate their culture in the file name. Например, при добавлении файла ресурсов с именем Resources.resx можно также создать файлы ресурсов с именами Resources.en-US.resx и Resources.fr-FR.resx, чтобы сохранить локализованные ресурсы для английского (США) и французского (Франция) языков и региональных параметров соответственно. For example, if you add a resource file named Resources.resx, you might also create resource files named Resources.en-US.resx and Resources.fr-FR.resx to hold localized resources for the English (United States) and French (France) cultures, respectively. Следует также указать язык и региональные параметры по умолчанию для приложения. You should also designate your application’s default culture. Это язык и региональные параметры, ресурсы которых используются в том случае, если для конкретного языка и региональных параметров никаких локализованных ресурсов обнаружить не удается. This is the culture whose resources are used if no localized resources for a particular culture can be found. Чтобы задать язык и региональные параметры по умолчанию, в обозревателе решений Visual Studio щелкните правой кнопкой мыши имя проекта, выберите «Приложение», щелкните Сведения о сборке и в списке Нейтральный язык выберите соответствующий язык и региональные параметры. To specify the default culture, in Solution Explorer in Visual Studio, right-click the project name, point to Application, click Assembly Information, and select the appropriate language/culture in the Neutral language list.

Во время компиляции среда Visual Studio сначала преобразует RESX-файлы проекта в двоичные файлы ресурсов (RESOURCES) и сохраняет их в подкаталоге каталога obj проекта. At compile time, Visual Studio first converts the .resx files in a project to binary resource (.resources) files and stores them in a subdirectory of the project’s obj directory. Visual Studio внедряет любые файлы ресурсов, не содержащие локализованные ресурсы, в основную сборку, созданную проектом. Visual Studio embeds any resource files that do not contain localized resources in the main assembly that is generated by the project. Если в каких-либо файлах ресурсов есть локализованные ресурсы, Visual Studio внедряет их в отдельные вспомогательные сборки для каждого локализованного языка и региональных параметров. If any resource files contain localized resources, Visual Studio embeds them in separate satellite assemblies for each localized culture. Затем Visual Studio сохраняет каждую вспомогательную сборку в каталоге, имя которого соответствует локализованному языку и региональным параметрам. It then stores each satellite assembly in a directory whose name corresponds to the localized culture. Например, локализованные ресурсы английского языка (США) сохраняются во вспомогательной сборке в подкаталоге en-US. For example, localized English (United States) resources are stored in a satellite assembly in the en-US subdirectory.

Читайте также:  Инициализация диска для установки windows
Оцените статью