C# 用C语言提取嵌入式资源#
我的C#可执行文件中嵌入了四个资源文件,一个python脚本和三个perl脚本。我可以成功地提取所有三个perl脚本。但是我无法提取python脚本。我试了很多方法。谁能看一下吗?多谢各位C# 用C语言提取嵌入式资源#,c#,embedded-resource,C#,Embedded Resource,我的C#可执行文件中嵌入了四个资源文件,一个python脚本和三个perl脚本。我可以成功地提取所有三个perl脚本。但是我无法提取python脚本。我试了很多方法。谁能看一下吗?多谢各位 public static string ExtractResource(string resourceName) { string destFile = ""; //look for the resource name foreach (string currentResource
public static string ExtractResource(string resourceName)
{
string destFile = "";
//look for the resource name
foreach (string currentResource in System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames() )
if (currentResource.LastIndexOf(resourceName) != -1)
{
string subPath = Common_Utilities.GetTempPath() + "SCRIPTS";
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
string strFile = subPath + "\\" + resourceName;
string path = System.IO.Path.GetDirectoryName(strFile);
string rootName = System.IO.Path.GetFileNameWithoutExtension(strFile);
destFile = path + @"\" + rootName + System.IO.Path.GetExtension(currentResource);
System.IO.Stream fs = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream( currentResource ) ;
byte[] buff = new byte[fs.Length];
fs.Read(buff, 0, (int)fs.Length);
fs.Close();
System.IO.FileStream destStream = new System.IO.FileStream(destFile, FileMode.Create);
destStream.Write(buff, 0, buff.Length);
destStream.Close();
}
return destFile;
// throw new Exception("Resource not found : " + resourceName);
}
不确定为什么无法提取Python脚本。。。。不过有两点:
Path.Combine()
将路径和文件名粘在一起-不要自己这样做,太多可能出错 System.IO.Stream fs = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(currentResource);
string scriptContents = new StreamReader(fs).ReadToEnd();
File.WriteAllText(destFile, scriptContents);
使用这种方法,您应该能够在调试中很容易地看到脚本是否正确地从资源中加载。如果没有-检查您的资源名称等(脚本是否真的设置为“嵌入式”资源?)。如果您的资源有子目录,请注意,资源名称将包含这些子目录,作为完全限定名称的一部分-但以点(
)分隔,而不是像物理路径那样的反斜杠你可以用简单的方法修改你的代码
Binary files -> File.WriteAllBytes(Path, Properties.Resources.filename);
Text files -> File.WriteAllText(Path, Properties.Resources.filename);
哪一行抛出了错误?请不要将代码示例或示例数据放入注释中-因为您无法格式化它,所以读取它非常困难。。。。取而代之的是:通过编辑你的问题来更新它,以提供额外的信息!谢谢。我的问题是,它没有进入该特定资源的if语句。对于所有其他资源,它都放在if语句中,运行良好。@baby_coder:那么您得到的这四个资源名称是什么?查看它们,找出Python脚本与您的
IF
子句不匹配的原因(IF子句到底应该做什么?)我修改了Python脚本的资源名称,如当前资源中所示,现在它正在正确提取。没有代码更改。谢谢marc_和所有其他人。请提供一些解释和上下文以及您的答案,以帮助其他用户理解它!谢谢你的贡献。