您的位置:首页 > 其它

嵌入资源第三讲:多格式文件内嵌入WPF资源文件

2014-06-02 22:07 253 查看
作为一个扩展,你需要了解DotNetZip用法,请参见:
C# .NET 使用第三方类库DotNetZip解压/压缩Zip文件

你也需要了解单文件内嵌入资源文件基本方法,参见:
WPF调用嵌入的非.net的EXE资源文件

作者:一剑

如果你有一大堆文件或者想通过打包的方式嵌入任意格式的文件到资源文件中,那么你可以打包成一个ZIP文件,再嵌入到资源文件中是一个不错的选择:

using Ionic.Zip;//+
using System.Reflection;
using System.IO;
using System.Threading;

namespace WpfApplication2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
List<string> fileList = new List<string>();
public MainWindow()
{
InitializeComponent();

Thread t = new Thread(new ThreadStart(unzip));
t.IsBackground = true;
t.Start();
}

private void unzip()
{
String projectName = Assembly.GetExecutingAssembly().GetName().Name.ToString();
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(projectName + ".f.zip"))
{
Byte[] b = new Byte[stream.Length];
stream.Read(b, 0, b.Length);
MemoryStream m = new MemoryStream(b);
using (ZipFile zip = ZipFile.Read(m))
{
zip.ExtractAll(System.IO.Path.GetTempPath(), ExtractExistingFileAction.OverwriteSilently);
foreach (ZipEntry entry in zip)
{
fileList.Add(System.IO.Path.GetTempPath() + entry.FileName);
}
}
}
}

private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (string f in fileList)
{
if (File.Exists(f))
MessageBox.Show(f + " is found.");
}
}

private void Window_Closed(object sender, EventArgs e)
{foreach (string f in fileList)
{
if (File.Exists(f))
File.Delete(f);
}
}
}
}


在这篇示例中,在程序结束时加入了ZIP中文件的遍历及清理,使得使用过后不留痕迹,把活干得漂亮点^_^。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: