[英]Error extracting a file from a program C#
我以前曾在我的程序中嵌入過文件,並獲得了圓滿成功,但是現在我將代碼行轉移到了另一個程序,但令我感到失望的是,我無法讓它在我的一生中都能正常工作。
提取代碼為:
private static void Extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
要提取我想要位於名為NewFolder1的文件夾中的程序,請輸入代碼:
Type myType = typeof(NewProgram);
var n = myType.Namespace.ToString();
String TempFileLoc = System.Environment.GetEnvironmentVariable("TEMP");
Extract(n, TempFileLoc, "NewFolder1", "Extract1.exe");
我可以毫無錯誤地編譯程序,但是一旦程序到達提取的行:
Extract(n, TempFileLoc, "NewFolder1", "Extract1.exe");
程序崩潰,出現錯誤:“值不能為空”
是的,我包含了System.IO和System.Reflection
有幾件事。
首先,您可能應該添加一些錯誤檢查,以便找出問題出在哪里。 而不是:
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." +
(internalFilePath== "" ? "" : internalFilePath + ".") + resourceName))
寫:
string name = nameSpace + "." +
(internalFilePath== "" ? "" : internalFilePath + ".") + resourceName;
Stream s = assembly.GetManifestResourceStream(name);
if (s == null)
{
throw new ApplicationException(); // or whatever
}
using (s)
{
// other stuff here
}
打開FileStream
時應該做同樣的事情。
如果進行了這些更改,則可以單步調試器或編寫代碼以輸出跟蹤信息,這些信息可以告訴您確切的錯誤發生位置。
其次,這里不需要BinaryReader
或BinaryWriter
。 你可以寫:
s.CopyTo(fs);
它將復制整個流內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.