KGy SOFT

ResXResourceWriter Class

KGy SOFT Core Libraries Help
Writes resources in an XML resource (.resx) file or an output stream.
See the Remarks section for an example and for the differences compared to System.Resources.ResXResourceWriter class.
Inheritance Hierarchy

SystemObject
  KGySoft.ResourcesResXResourceWriter

Namespace:  KGySoft.Resources
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0-rc.1
Syntax

public sealed class ResXResourceWriter : IResourceWriter, 
	IDisposable

The ResXResourceWriter type exposes the following members.

Constructors

  NameDescription
Public methodResXResourceWriter(Stream, FuncType, String)
Initializes a new instance of the ResXResourceWriter class that writes the resources to a specified stream.
Public methodResXResourceWriter(TextWriter, FuncType, String)
Initializes a new instance of the ResXResourceWriter class that writes the resources by a specified textWriter.
Public methodResXResourceWriter(String, FuncType, String)
Initializes a new instance of the ResXResourceWriter class that writes the resources to a specified file.
Top
Properties

  NameDescription
Public propertyAutoGenerateAlias
Gets or sets whether an alias should be auto-generated for referenced assemblies.
Default value: .
Public propertyBasePath
Gets or sets the base path for the relative file path specified in a ResXFileRef object.
Public propertyCompatibleFormat
Gets or sets whether the ResXResourceWriter instance should create a System compatible .resx file, which can be used by the built-in resource editor of the Visual Studio.
Default value: .
See the Remarks section for details.
Public propertyOmitHeader
Gets or sets whether the header should be omitted. If both CompatibleFormat and OmitHeader are , then only the XML comment will be omitted. If CompatibleFormat is  and OmitHeader is , then the comment, the .resx schema and the <resheader> elements will be omitted, too.
Default value: .
Top
Methods

  NameDescription
Public methodAddAlias(String, AssemblyName, Boolean)
Adds the specified alias to the mapping of aliases.
Public methodAddAlias(String, String, Boolean)
Adds the specified alias to the mapping of aliases.
Public methodAddMetadata(ResXDataNode)
Adds a metadata node specified in a ResXDataNode object to the list of resources to write.
Public methodAddMetadata(String, Byte)
Adds a metadata node whose value is specified as a byte array to the list of resources to write.
Public methodAddMetadata(String, Object)
Adds a metadata node whose value is specified as an object to the list of resources to write.
Public methodAddMetadata(String, String)
Adds a metadata node whose value is specified as a string to the list of resources to write.
Public methodAddResource(ResXDataNode)
Adds a named resource specified in a ResXDataNode object to the list of resources to write.
Public methodAddResource(String, Byte)
Adds a named resource specified as a byte array to the list of resources to write.
Public methodAddResource(String, Object)
Adds a named resource specified as an object to the list of resources to write.
Public methodAddResource(String, String)
Adds a string resource to the resources.
Public methodClose
Releases all resources used by the ResXResourceWriter. If content has not been saved yet (see Generate method), then firstly flushes any remaining content.
Public methodDispose
Releases all resources used by the ResXResourceWriter.
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Protected methodFinalize
This member overrides the Finalize method.
(Overrides ObjectFinalize.)
Public methodGenerate
Flushes all pending content into the output file, TextWriter or Stream.
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Extension Methods

  NameDescription
Public Extension MethodConvert(Type, CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions.)
Public Extension MethodCode exampleConvertTTarget(CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions.)
Public Extension MethodIn (Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, CultureInfo, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(CultureInfo, TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Top
Remarks

Note Note
This class is similar to System.Resources.ResXResourceWriter in System.Windows.Forms.dll. See the Comparison with System.Resources.ResXResourceWriter section for the differences.
Tip Tip
To see when to use the ResXResourceReader, ResXResourceWriter, ResXResourceSet, ResXResourceManager, HybridResourceManager and DynamicResourceManager classes see the documentation of the KGySoft.Resources namespace.

Resources are specified as name/value pairs using the AddResource method.

If CompatibleFormat property is , ResXResourceWriter emits .resx files, which can be then read not just by ResXResourceReader but by the original System.Resources.ResXResourceReader class, too.

Examples

The following example shows how to create a resource file by ResXResourceWriter and add different kind of resource objects to it. At the end it displays the resulting .resx file content.
C#
using System;
using System.Drawing;
using System.IO;
using KGySoft.Resources;

public class Example
{
    [Serializable]
    private class MyCustomClass
    {
        public string StringProp { get; set; }
        public int IntProp { get; set; }
    }

    public static void Main()
    {
        // Check the result with CompatibleFormat = true as well.
        // You will get a much longer result, which will be able to read by System.Resources.ResXResourceReader, too.
        var result = new StringWriter();
        using (var writer = new ResXResourceWriter(result) { CompatibleFormat = false })
        {
            writer.AddResource("string", "string value");
            writer.AddResource("int", 42);
            writer.AddResource("null", (object)null);
            writer.AddResource("file", new ResXFileRef(@"images\Image.jpg", typeof(Bitmap)));
            writer.AddResource("custom", new MyCustomClass { IntProp = 42, StringProp = "blah" });
        }

        Console.WriteLine(result.GetStringBuilder());
    }
}

// The example displays the following output:
// <?xml version="1.0" encoding="utf-8"?>
// <root>
//   <data name="string">
//     <value>string value</value>
//   </data>
//   <data name="int" type="System.Int32">
//     <value>42</value>
//   </data>
//   <assembly alias="KGySoft.CoreLibraries" name="KGySoft.CoreLibraries, Version=3.6.3.1, Culture=neutral, PublicKeyToken=b45eba277439ddfe" />
//   <data name="null" type="KGySoft.Resources.ResXNullRef, KGySoft.CoreLibraries">
//     <value />
//   </data>
//   <data name="file" type="KGySoft.Resources.ResXFileRef, KGySoft.CoreLibraries">
//     <value>images\Image.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
//   </data>
//   <data name="custom" mimetype="text/kgysoft.net/object.binary.base64">
//     <value>
//       PgAChAQFQkNvbnNvbGVBcHAxLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbBVF
//       eGFtcGxlK015Q3VzdG9tQ2xhc3MBAhs8U3RyaW5nUHJvcD5rX19CYWNraW5nRmllbGQDEgAEYmxhaBg8SW50UHJvcD5rX19CYWNr
//       aW5nRmllbGQECEAqAA==
//     </value>
//   </data>
// </root>

Comparison with System.Resources.ResXResourceWriter 

Note Note
When writing a .resx file in CompatibleFormat, the System.Windows.Forms.dll is not loaded when referencing System.Resources.ResXFileRef and System.Resources.ResXNullRef types.

Incompatibility with System.Resources.ResXResourceWriter:

  • The System version has several public string fields, which are not intended to be accessed by a consumer code. Therefore the following fields are missing (they are not public) in this version:
    • BinSerializedObjectMimeType
    • ByteArraySerializedObjectMimeType
    • DefaultSerializedObjectMimeType
    • ResMimeType
    • ResourceSchema
    • SoapSerializedObjectMimeType
    • Version
  • In this version there are no one parameter constructors. Instead, the second parameter (typeNameConverter) is optional. If used purely from C# (no reflection or whatsoever), this change is a compatible one.
  • This ResXResourceWriter is a sealed class.
  • After disposing the ResXResourceWriter instance or calling the Close method, calling the Generate method will throw an ObjectDisposedException.
  • The System.Resources.ResXResourceWriter.AddAlias method just populates an inner alias list causing that the alias will be recognized on further processing but will never be dumped into the output stream. In this ResXResourceWriter implementation the AddAlias method is somewhat different: not just registers the alias as a known one but also dumps that into the output stream. It can be specified though, whether the dump should be deferred until the alias is actually referenced for the first time.

New features and improvements compared to System.Resources.ResXResourceWriter:

  • Compatibility - If CompatibleFormat is , the resulting .resx file can be read by System.Resources.ResXResourceReader.
  • Compactness - The more compact output is achieved in multiple ways:
    • If OmitHeader is , the header and the schema is not dumped into the resulting .resx file. If CompatibleFormat is , then only the header comment can be omitted.
    • Whitespace preserving to string values is applied only if it is really necessary (even if CompatibleFormat is ).
    • If an object can only be binary serialized, then instead of using BinaryFormatter it is serialized by BinarySerializationFormatter, which produces a much more compact result (only if CompatibleFormat is ). A new MIME type has been introduced to identify binary data serialized this new way.
  • New overloads:
    • AddAlias method now can be called with a String assembly name and not just by an AssemblyName instance. Both overloads have now an optional Boolean argument for specifying whether the alias must be dumped immediately.
    • New AddMetadata(ResXDataNode) overload, working similarly to the existing AddResource(ResXDataNode) method.
  • AutoGenerateAlias property - If , alias names for assemblies will be automatically generated without calling AddAlias method. If , the assembly qualified names will be used for non-mscorlib types, unless an alias name was explicitly added by the AddAlias method or the ResXDataNode to dump already contains an alias name.
  • Better support of several types:
    TypeImprovementHow it is handled by the System version
     valueInvalid .resx representations of  value is fixed when re-written by ResXResourceWriter. When the System version rewrites such an invalid  node, it turns into empty string.
    Array of SByteSerializing sbyte[] type works properly.The System.Resources.ResXResourceWriter changes the sbyte[] types to byte[].
    CharSupport of unpaired surrogate characters.System.Resources.ResXResourceWriter cannot serialize unpaired surrogates, though System.Resources.ResXResourceReader can read them successfully if they are serialized by ResXResourceWriter and CompatibleFormat is .
    String and any type serialized by a TypeConverter.Strings containing unpaired surrogates and invalid Unicode characters can be written without any error.System.Resources.ResXResourceWriter cannot serialize such strings, though System.Resources.ResXResourceReader can read them successfully if they are serialized by ResXResourceWriter and CompatibleFormat is .
    DateTime and DateTimeOffsetSerialized in a different way so even the milliseconds part is preserved.The fixed form can be deserialized by System.Resources.ResXResourceReader, too; however, the DateTime.Kind will be always Local.
    Single, Double and Decimal-0 (negative zero) value is handled correctly.The fixed form can be deserialized by System.Resources.ResXResourceReader, too; however, in case of Single and Double -0 will always turn to +0.
    IntPtr, UIntPtr, DBNull and Type instances containing a runtime type (which is not a generic type argument).These types are supported natively (without a mimetype attribute). Only if CompatibleFormat is .System.Resources.ResXResourceWriter can serialize these type only by BinaryFormatter.
    Generic typesGeneric types with a TypeConverter are handled correctly.Parsing generic type names may fail with System.Resources.ResXResourceReader. The problem does not occur on binary serialization because in that case the type name is not dumped into the .resx file but is encoded in the binary stream.
    Any non-serializable typeAs long as the BinarySerializationFormatter can serialize the non-serializable type, this implementation supports non-serializable types as well. This works even if CompatibleFormat is .If CompatibleFormat is  during serialization, deserialization works even with System.Resources.ResXResourceReader as long as KGySoft.CoreLibraries assembly can be loaded and BinaryFormatter can find the AnyObjectSerializerWrapper class.

See Also

Reference