2017-03-07 382 views
0

我在项目的根文件夹下有证书。项目名称是SingleSignOn,但我无法使用GetManifestResourceStream内置方法读取该方法。使用C#使用Assembly GetManifestResourceStream方法读取资源文件

源代码是

namespace SingleSignOn 
{ 
    public class Program 
    { 
     static void Main(string[] args) 
     { 
      var assembly = typeof(Program).Assembly; 
      var super = assembly.GetManifestResourceNames(); 
      using (var stream = assembly.GetManifestResourceStream("SingleSignOn.idsrv3test.pfx")) 
      { 

      } 
     } 
    } 
} 
Solution Explorer中 enter image description here

我越来越从上述内置方法NULL

快照GetManifestResourceStream

enter image description here

我不我不知道我错过了什么。该证书的网址是https://github.com/IdentityServer/IdentityServer3.Samples/blob/master/source/Certificates/idsrv3test.pfx

请帮助我如何阅读证书。

+0

右键单击pfx文件 - >属性 - >生成操作,使其成为'嵌入资源' –

+0

为什么要读取该密钥? .net签名会自动完成。 –

+0

该程序集的默认名称空间(项目属性中的名称空间)是什么?因为GetManifestResourceStream用来定位资源。 – Evk

回答

1

证书试试这个:

var resourceName = "SingleSignOn.idsrv3test.pfx"; 
      using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) 
      { 
       TextReader tr = new StreamReader(stream); 
       string fileContents = tr.ReadToEnd(); 
      } 

注:将文件作为嵌入式资源。文件>右键单击>属性>构建操作>选择嵌入的资源。

+0

得到执行组件的速度很慢 – Developerdeveloperdeveloper

1

确保该文件是“嵌入的资源”。 Right click the pfx file -> Properties -> Build Action,使其成为'嵌入式资源'

1

PFX是一个容器,可容纳一个或多个证书。您可以使用下面的代码

X509Certificate2Collection collection = new X509Certificate2Collection(); 
collection.Import("idsrv3test.pfx", "password-for-pfx", X509KeyStorageFlags.PersistKeySet); 

在C#中打开它们现在遍历集合,并找到你所需要

foreach (X509Certificate2 cert in collection) 
{ 
    // work with cert 
} 
1

溶液2

步骤1:.PFX的变化属性文件 idsrv3test.pfx属性,设置生成动作作为嵌入的资源。

第2步:代码变化: -

var resourceName = "SingleSignOn.idsrv3test.pfx"; 
      using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) 
      { 
       TextReader tr = new StreamReader(stream); 
       string fileContents = tr.ReadToEnd(); 
      } 
1

我个人的做法是编写大会类的延伸,因为这似乎是应该已经包含在类反正的方法。

所以,正如其他海报提到,首先要确保你的文本文件被标记为“嵌入的资源”,然后使用类似的代码如下:

public static class Extensions 
{ 
    public static string ReadTextResource(this Assembly asm, string resName) 
    { 
     string text; 
     using (Stream strm = asm.GetManifestResourceStream(resName)) 
     { 
      using (StreamReader sr = new StreamReader(strm)) 
      { 
       text = sr.ReadToEnd(); 
      } 
     } 
     return text; 
    } 
} 

(以上可以更简洁地编码,但我以此为示范)