using System;
using System.IO;
using System.Reflection;
using ConsoleTables;
namespace EmbeddedFileExtractor
{
public static class ResourceExtractor
{
public static bool ExtractResourceToFile(string resourceName, string targetFilePath)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resourceNames = assembly.GetManifestResourceNames();
if (!Array.Exists(resourceNames, r => r == resourceName))
{
Console.WriteLine("指定的资源未找到.");
return false;
}
Stream stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
Console.WriteLine("未能获取资源流.");
return false;
}
try
{
using (FileStream fileStream = new FileStream(targetFilePath, FileMode.Create))
{
stream.CopyTo(fileStream);
}
Console.WriteLine("已成功释放: {0}", resourceName);
return true;
}
catch (Exception ex)
{
Console.WriteLine("文件释放失败: {0}", ex.Message);
return false;
}
}
}
class Program
{
static void 释放(KeyValuePair<string, List<string>> kvp)
{
string key = kvp.Key;
string name = "自释放." + key;
string targetPath = Path.Combine(Directory.GetCurrentDirectory(), "自释放" , key);
string directoryPath = Path.GetDirectoryName(targetPath);
if (directoryPath != null && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine("目录不存在,已创建");
}
ResourceExtractor.ExtractResourceToFile(name,targetPath);
}
static void 废话(){
Console.WriteLine("按任意键退出");
Console.ReadKey();
}
static void Main(string[] args)
{
Dictionary<string, List<string>> files = new Dictionary<string, List<string>>();
files.TryAdd("六构图.pdf", new List<string> { "几个化学结构式" });
if (args.Length >0)
{
foreach (var kvp in files)
{
string name = kvp.Key;
释放(kvp);
}
Console.WriteLine("释放完毕");
废话();
}
ConsoleTable table = new ConsoleTable("文件名", "描述");
Console.WriteLine("编译日期: ");
foreach (var kvp in files)
{
string name = kvp.Key;
List<string> info = kvp.Value;
table.AddRow(name, info[0]);
}
table.Write();
Console.WriteLine();
Console.WriteLine("是否进行释放操作(Y/N)");
ConsoleKeyInfo Is_next = Console.ReadKey();
Console.WriteLine();
if (Is_next.Key == ConsoleKey.Y || Is_next.Key == ConsoleKey.Y /* 大写Y */)
{
foreach (var kvp in files)
{
string name = kvp.Key;
释放(kvp);
}
Console.WriteLine("释放完毕");
废话();
}
else if (Is_next.Key == ConsoleKey.N || Is_next.Key == ConsoleKey.N /* 大写Y */)
{
Console.WriteLine("释放已取消");
废话();
}
else
{
Console.WriteLine("无效的输入");
废话();
}
}
}
}
如题,这段代码会将内嵌在项目中的文件释放出来,并配有一个控制台列表来展示文件名和文件描述,但需要手动配置files字典来配置文件列表
注意要把文件属性改成“内嵌的资源”