December 2007
Intermediate to advanced
896 pages
19h 57m
English
You need to find all the serializable types within an assembly.
Instead of testing the implemented interfaces and attributes on every type, you can query the Type.IsSerialized property to determine whether it is marked as serializable, as the following method does:
public static IEnumerable<string> GetSerializableTypeNames(string asmPath)
{
Assembly asm = Assembly.LoadFrom(asmPath);
return from type in asm.GetTypes()
where type.IsSerializable
select type.FullName;
}The GetSerializableTypeNames method accepts an Assembly through its asm parameter. This assembly is searched for any serializable types, and their full names (including namespaces) are returned in an IEnumerable<Type>.
In order to use this method to display the serializable types in an assembly, run the following code:
public static void FindSerializable()
{
Process current = Process.GetCurrentProcess();
// get the path of the current module
string asmPath = current.MainModule.FileName;
IEnumerable<string> typeNames = GetSerializableTypeNames(asmPath);
// write out the serializable types in the assembly
if(typeNames.Count() > 0)
{
Console.WriteLine("{0} has serializable types:",asmPath);
foreach(string typeName in typeNames)
{
Console.WriteLine("\t{0}",typeName);
}
}
}The output of this method is shown here:
C:\CSharp Recipes 2nd Edition\Code\CSharpRecipes\bin\Debug\CSharpRecipes.exe has serializable types: CSharpRecipes.ExceptionHandling+RemoteComponentException ...
Read now
Unlock full access