toFile

Serializes data to a file.

Any format supported by this library may be specified. If no format is specified, it will be chosen from the file extension if possible.

Supports $(SUPPORTEDSTRUCTURES).

This function will NOT create directories as necessary.

@property
void
toFile
(
Format = AutoDetect
Siryulize flags = Siryulize.none
T
)
(,
string path
)
if (
isSiryulizer!Format ||
is(Format == AutoDetect)
)

Parameters

Format

Serialization format ($(SUPPORTEDFORMATS))

data T

The data to be serialized

path string

The path for the file to be written

Examples

import std.exception : assertThrown;
import std.file : exists, remove;
struct TestStruct {
	string a;
}
scope(exit) { //Clean up when done
	if ("int.yml".exists) {
		remove("int.yml");
	}
	if ("string.json".exists) {
		remove("string.json");
	}
	if ("struct.yml".exists) {
		remove("struct.yml");
	}
	if ("int-auto.yml".exists) {
		remove("int-auto.yml");
	}
	if ("string-auto.json".exists) {
		remove("string-auto.json");
	}
	if ("struct-auto.yml".exists) {
		remove("struct-auto.yml");
	}
}
//Write the integer "3" to "int.yml"
3.toFile!YAML("int.yml");
//Write the string "str" to "string.json"
"str".toFile!JSON("string.json");
//Write a structure to "struct.yml"
TestStruct("b").toFile!YAML("struct.yml");

//Check that contents are correct
assert("int.yml".fromFile!uint == 3);
assert("string.json".fromFile!string == "str");
assert("struct.yml".fromFile!TestStruct == TestStruct("b"));

//Write the integer "3" to "int-auto.yml", but detect format automatically
3.toFile("int-auto.yml");
//Write the string "str" to "string-auto.json", but detect format automatically
"str".toFile("string-auto.json");
//Write a structure to "struct-auto.yml", but detect format automatically
TestStruct("b").toFile("struct-auto.yml");

//Check that contents are correct
assert("int-auto.yml".fromFile!uint == 3);
assert("string-auto.json".fromFile!string == "str");
assert("struct-auto.yml".fromFile!TestStruct == TestStruct("b"));

//Bad extension for auto-detection mechanism
assertThrown(3.toFile("file.obviouslybadextension"));

Meta