Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing and reading a type value to/from file

Tags:

c#

types

io

I need to be able to store a type value into a file, and read it back into a type value later. What's the best way to go about this?

Type type = typeof(SomeClass);
binaryWriter.Write?(type);
like image 792
Villermen Avatar asked Jan 23 '26 12:01

Villermen


1 Answers

I'd store the assembly-qualified name, assuming the assembly will still be present later:

binaryWriter.Write(type.AssemblyQualifiedName);
...
string typeName = binaryReader.ReadString();
Type type = Type.GetType(typeName);

If you already know what assembly the type will be in, you could just use the full name (i.e. namespace and type name, but not assembly). Then use Assembly.GetType(string) later.

like image 67
Jon Skeet Avatar answered Jan 25 '26 02:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!