我一直在使用的一个应用程序在尝试序列化类型时失败了。

像这样的陈述

XmlSerializer lizer = new XmlSerializer(typeof(MyType));

生产:

System.IO.FileNotFoundException occurred
  Message="Could not load file or assembly '[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified."
  Source="mscorlib"
  FileName="[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
  FusionLog=""
  StackTrace:
       at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
       at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)

我没有为我的类定义任何特殊的序列化器。

我该如何解决这个问题?


当前回答

您的类型可能会引用在GAC和本地bin文件夹中都找不到的其他程序集==>…

或其依赖项之一。该系统 无法找到指定的文件"

您能举例说明要序列化的类型吗?

注意:确保你的类型实现Serializable。

其他回答

我遇到了这个问题,上面提到的任何解决方案都无法解决它。

后来我终于找到了解决办法。 序列化器似乎不仅需要类型,还需要嵌套类型。 改变:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T).GetNestedTypes());

为我修正了这个问题。 没有什么例外。

我的解决方案是直接使用反射来创建序列化器。这就绕过了导致异常的奇怪文件加载。我将其打包在一个helper函数中,该函数还负责缓存序列化器。

private static readonly Dictionary<Type,XmlSerializer> _xmlSerializerCache = new Dictionary<Type, XmlSerializer>();

public static XmlSerializer CreateDefaultXmlSerializer(Type type) 
{
    XmlSerializer serializer;
    if (_xmlSerializerCache.TryGetValue(type, out serializer))
    {
        return serializer;
    }
    else
    {
        var importer = new XmlReflectionImporter();
        var mapping = importer.ImportTypeMapping(type, null, null);
        serializer = new XmlSerializer(mapping);
        return _xmlSerializerCache[type] = serializer;
    }
}

Like Martin Sherburn said, this is normal behavior. The constructor of the XmlSerializer first tries to find an assembly named [YourAssembly].XmlSerializers.dll which should contain the generated class for serialization of your type. Since such a DLL has not been generated yet (they are not by default), a FileNotFoundException is thrown. When that happenes, XmlSerializer's constructor catches that exception, and the DLL is generated automatically at runtime by the XmlSerializer's constructor (this is done by generating C# source files in the %temp% directory of your computer, then compiling them using the C# compiler). Additional constructions of an XmlSerializer for the same type will just use the already generated DLL.

更新:从。net 4.5开始,XmlSerializer不再执行代码生成,也不再为了在运行时创建序列化程序集而使用c#编译器执行编译,除非通过设置配置文件设置(useLegacySerializerGeneration)显式强制执行。此更改消除了对csc.exe的依赖,并提高了启动性能。来源:. net Framework 4.5 Readme,章节1.3.8.1。

异常由XmlSerializer的构造函数处理。你不需要自己做任何事情,你可以点击“继续”(F5)继续执行你的程序,一切都会好的。如果你被异常停止程序执行并弹出异常助手所困扰,你要么关闭“只是我的代码”,要么将FileNotFoundException设置为在抛出时中断执行,而不是在“User-unhandled”时。

打开“Just My Code”,请转到“Tools >> Options >> Debugging >> General >> enable Just My Code”。要关闭FileNotFound被抛出时的执行中断,请转到调试>>异常>>找到>>输入'FileNotFoundException' >>取消System.IO.FileNotFoundException中的' thrown '复选框。

为了避免异常,你需要做两件事:

向序列化类添加属性(我希望您有访问权限) 使用sgen.exe生成序列化文件

将System.Xml.Serialization.XmlSerializerAssembly属性添加到类中。 将'MyAssembly'替换为MyClass所在程序集的名称。

[Serializable]
[XmlSerializerAssembly("MyAssembly.XmlSerializers")]
public class MyClass
{
…
}

使用sgen.exe实用程序生成序列化文件,并将其与类的程序集一起部署。

' sgen.exe MyAssembly.dll '将生成文件myassembly . xmlserializer .dll

这两个更改将导致.net直接查找程序集。 我检查了一下,它在。net框架3.5和Visual Studio 2008上工作

另一方面,对编译错误进行故障排除是非常复杂的。这些问题在FileNotFoundException异常中显示,并显示如下信息:

File or assembly name abcdef.dll, or one of its dependencies, was not found. File name: "abcdef.dll"
   at System.Reflection.Assembly.nLoad( ... )
   at System.Reflection.Assembly.InternalLoad( ... )
   at System.Reflection.Assembly.Load(...)
   at System.CodeDom.Compiler.CompilerResults.get_CompiledAssembly() 

You may wonder what a file not found exception has to do with instantiating a serializer object, but remember: the constructor writes C# files and tries to compile them. The call stack of this exception provides some good information to support that suspicion. The exception occurred while the XmlSerializer attempted to load an assembly generated by CodeDOM calling the System.Reflection.Assembly.Load method. The exception does not provide an explanation as to why the assembly that the XmlSerializer was supposed to create was not present. In general, the assembly is not present because the compilation failed, which may happen because, under rare circumstances, the serialization attributes produce code that the C# compiler fails to compile.

请注意 当XmlSerializer在不能访问临时目录的帐户或安全环境下运行时,也会发生此错误。

来源: http://msdn.microsoft.com/en-us/library/aa302290.aspx