1

如何将文件夹与一键式应用程序捆绑在一起并在之后引用这些文件/文件夹?

看起来很简单,但我就是不知道怎么做。

例如,我在文件index.html夹中有文件UI,我想将它与应用程序打包,然后我想用字符串"/UI/index.html"而不是index.html整个网站获取该文件的流。

4

2 回答 2

2

将文件夹添加到您的 VS 项目中,右键单击它并选择“嵌入为资源”。这将使文件夹中的文件嵌入到 .NET 程序集中。要获取程序中的文件内容,您可以使用以下内容:

public class ReadResource
{
    public string ReadInEmbeddedFile (string filename) {
        // assuming this class is in the same assembly as the resource folder
        var assembly = typeof(ReadResource).Assembly;

        // get the list of all embedded files as string array
        string[] res = assembly.GetManifestResourceNames ();

        var file = res.Where (r => r.EndsWith(filename)).FirstOrDefault ();

        var stream = assembly.GetManifestResourceStream (file);
        string file_content = new StreamReader(stream).ReadToEnd ();

        return file_content;
     }
}

在上述函数中,我假设您的文件是 text/html 文件;如果没有,您可以将其更改为不返回字符串而是返回 byte[],并为此使用二进制流阅读器。我还选择了file.EndsWith()足以满足我需求的文件;如果您的文件夹具有深层嵌套结构,则需要修改该代码以解析文件夹级别。

于 2013-02-10T09:47:14.510 回答
1

也许有更好的方法,但鉴于内容不是太大,您可以将二进制文件作为 base64 字符串直接嵌入到您的程序中。在这种情况下,它需要是文件夹的存档。您还需要嵌入用于解压缩该存档的 dll(如果我理解正确,您希望拥有单个 .exe,仅此而已)。

这是一个简短的例子

// create base64 strings prior to deployment
string unzipDll = Convert.ToBase64String(File.ReadAllBytes("Ionic.Zip.dll"));
string archive = Convert.ToBase64String(File.ReadAllBytes("archive.zip"));

string unzipDll = "base64string";
string archive = "probablyaverylongbase64string";

File.WriteAllBytes("Ionic.zip.dll", Convert.FromBase64String(unzipDll));
File.WriteAllBytes("archive.zip", Convert.FromBase64String(archive);

Ionic.Zip.ZipFile archive = new Ionic.Zip.ZipFile(archiveFile);
archive.ExtractAll("/destination");

解压库是 DotNetZip。这很好,因为您只需要一个 dll。http://dotnetzip.codeplex.com/downloads/get/258012

编辑:想一想,只要将 Ionic.dll 写入 .exe 的工作目录,就不需要使用动态 dll 加载,所以我删除了该部分以简化答案(它仍然需要在你达到它的方法之前写)。

于 2013-02-10T09:31:24.123 回答