WPF 释放嵌入资源,自制安装程序必备

文件记得要设置嵌入资源,这很重要!

然后资源文件名称必须包含目录,目录间用“.”隔开,最外层是项目默认命名空间

例如嵌入了一个名为test.txt的文件,那就是:命名空间.text.txt,如果这个文件放在文件夹里,记得加上文件夹:命名空间.文件夹.text.txt

如果你不知道命名空间是啥,请先去学基础。

/// <summary>
/// 提取文件
/// </summary>
/// <param name="resFileName">资源文件名称</param>
/// <param name="outputFile">输出文件</param>
/// <returns>成功或失败</returns>
private bool ExtractResFile(string resFileName, string outputFile)
{
    BufferedStream inStream = null;
    FileStream outStream = null;
    try
    {
        Assembly asm = Assembly.GetExecutingAssembly(); //读取嵌入式资源
        inStream = new BufferedStream(asm.GetManifestResourceStream(resFileName));
        outStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write);

        byte[] buffer = new byte[1024];
        int length;

        while ((length = inStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            outStream.Write(buffer, 0, length);
        }
        outStream.Flush();
        return true;
    }
    catch
    {
        return false;
    }
    finally
    {
        if (outStream != null) outStream.Close();
        if (inStream != null) inStream.Close();
    }
}

留下评论