簡體   English   中英

c# 從資源中讀取字節數組

[英]c# read byte array from resource

我一直在試圖弄清楚如何從我的一個資源文件中讀取字節數組,我已經嘗試了谷歌上最受歡迎的點擊但沒有明顯的成功。

我有一個文件存儲在我的程序的資源集合中,我想將這個文件作為字節數組讀取

我目前正在使用以下代碼從程序的根目錄中讀取文件:

FileStream fs = new FileStream(Path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
fs.Close();
br.Close();

但是,我想將該文件作為資源存儲在我的應用程序中,這樣我就不必隨程序一起發送額外的文件。

該文件包含我的部分程序使用的加密數據。

任何幫助或指示將不勝感激!

假設您正在討論作為程序集中的資源嵌入的文件:

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream("SomeNamespace.somefile.png"))
{
    byte[] buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
    // TODO: use the buffer that was read
}

您可以通過項目屬性,“資源”選項卡(如果需要,創建一個),添加資源(現有文件),為應用程序添加資源。 添加文件后,可以將其FileType(在其屬性中)設置為Binary。

文檔

之后,您可以輕松地以字節[]的形式訪問您的文件:

var myByteArray = Properties.Resources.MyFile;
byte[] capacity = Properties.Resources.excel;

在此處輸入圖像描述

混亂: 在此處輸入圖像描述

在這里我們讀取 txt 資源文件。所以它不返回byte[]但它返回string (文件內容)。

var rm = new ResourceManager("RessourceFile", typeof(ClassXY).Assembly);
return Encoding.UTF8.GetBytes(rm.GetString("key"));

也許你可以嘗試使用StreamResourceInfo。 這是一個Silverlight示例的鏈接,但如果我沒有弄錯,您應該能夠在任何.NET應用程序中應用相同的原則:

http://msdn.microsoft.com/en-us/library/system.windows.resources.streamresourceinfo(v=VS.95).aspx

問候,
安德斯@Cureos

這是我們為此目的使用的一個小課程:

static class EmbeddedResource
{
    /// <summary>
    /// Extracts an embedded file out of a given assembly.
    /// </summary>
    /// <param name="assemblyName">The namespace of your assembly.</param>
    /// <param name="fileName">The name of the file to extract.</param>
    /// <returns>A stream containing the file data.</returns>
    public static Stream Open(string assemblyName, string fileName)
    {
        var asm = Assembly.Load(assemblyName);
        var stream = asm.GetManifestResourceStream(assemblyName + "." + fileName);

        if (stream == null)
            throw new ConfigurationErrorsException(String.Format(
                    Strings.MissingResourceErrorFormat, fileName, assemblyName));

        return stream;
    }
}

用法非常簡單:

using (var stream = EmbeddedResource.Open("Assembly.Name", "ResourceName"))
    // do stuff

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM