从程序集中读取xml文件

时间:2012-10-17 14:32:58

标签: c# xml winforms .net-assembly

我正在尝试从汇编中读取xml文件,这是我的代码:

private Assembly testAssembly;
    private void button1_Click(object sender, EventArgs e)
    {
        string testfile = "stack.xml";
        String testfileName = string.Format("{0}.{1}", testAssembly.GetName().Name, testfile);

        using (Stream stream = testAssembly.GetManifestResourceStream(testfileName))
        {
            using (StreamReader sr = new StreamReader(stream))
            {
                var value = sr.ReadToEnd();
                Console.WriteLine("The read file is {0}", value);
            }
        }
    }

我在这一行遇到了问题:

String testfileName = string.Format("{0}.{1}", testAssembly.GetName().Name, 
                                     testfile); 

Null ref异常未处理,它表示null。任何帮助???     enter image description here

2 个答案:

答案 0 :(得分:2)

看起来marksAssemblynull

答案 1 :(得分:1)

string resName = "resources/HistoryConnections.xml";  

private static UnmanagedMemoryStream GetResourceStream(string resName)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var strResources = assembly.GetName().Name + ".g.resources";
            var rStream = assembly.GetManifestResourceStream(strResources);
            var resourceReader = new ResourceReader(rStream);
            var items = resourceReader.OfType<DictionaryEntry>();
            var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
            return (UnmanagedMemoryStream)stream;
        }