2013-09-22 81 views
3

我使用的是.NET組件,使用期望與全路徑名這樣的字符串的方法讀取特定的二進制文件:C#獲取嵌入式資源的完整路徑?

Read("c:\\somefile.ext"); 

我已經把somefile.ext在嵌入式資源我的項目。有沒有什麼辦法可以將某種路徑傳遞給組件的Read命令的嵌入式資源?

+2

嵌入的資源不具有「全路徑名。」您不能像在文件系統中那樣使用文件路徑來引用它。你的組件是否有一個'Read'函數,它將採用'Stream'參數? –

+0

不幸的是它沒有。所以最簡單的選擇是不嵌入它和'複製到輸出目錄'?謝謝!亞歷克斯 – Corvinalex

回答

3

到資源的路徑是形式namespace.projectfolder.filename.ext的。

爲了閱讀的內容,你可以使用一個輔助類,像這樣的

public class ResourceReader 
{ 
    // to read the file as a Stream 
    public static Stream GetResourceStream(string resourceName) 
    { 
     Assembly assembly = Assembly.GetExecutingAssembly(); 
     Stream resourceStream = assembly.GetManifestResourceStream(resourceName); 
     return resourceStream; 
    } 

    // to save the resource to a file 
    public static void CreateFileFromResource(string resourceName, string path) 
    { 
     Stream resourceStream = GetResourceStream(resourceName); 
     if (resourceStream != null) 
     { 
      using (Stream input = resourceStream) 
      { 
       using (Stream output = File.Create(path)) 
       { 
        input.CopyTo(output); 
       } 
      } 
     } 
    } 
} 
+0

謝謝Shamp。這個幫助類可以很好地提取嵌入文件 – Corvinalex

+1

Stream類有一個CopyTo方法,可以用來代替你的CopyStream http://msdn.microsoft.com/en-us/library/dd782932.aspx – Jimmy

+0

謝謝@Jimmy。代碼已更新。 – shamp00

0

您需要使用項目的名稱空間以及嵌入資源的名稱。例如,假設somefile.ext位於名爲ProjectA的項目文件夾資源/文件中。該你應該使用閱讀嵌入式資源的正確字符串是:

ProjectA.resources.files.somefile.ext