2013-08-28 16 views
0

我在之前的程序中嵌入了文件,以前已經完全成功,但現在我已將代碼行轉移到第二個程序,並且對於我的失望,我只是無法讓它工作爲了我的生活。從程序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"); 

程序崩潰的d我得到一個錯誤:「值不能爲空」

是的,我包括System.IO &的System.Reflection

+0

您應該能夠使用Visual Studio調試器找出究竟是空的。通過調試運行代碼並逐步檢查獲取的值是否爲空。 –

+0

問題是調試器找不到任何東西,我只找到一個問題,一旦我嘗試運行程序來提取EXE。 –

+0

首先猜測是's'爲空。 'GetManifestResourceStream()'[doc](http://msdn.microsoft.com/en-us/library/xc4235zt.aspx)說:'清單資源;如果在編譯期間沒有指定資源,或者資源對調用者不可見,則爲null –

回答

1

幾件事情。

首先,您可能應該添加一些錯誤檢查,以便您可以找出問題所在。而不是:

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時,您應該做同樣的事情。

如果您進行了這些更改,您可以在調試器中單步執行或編寫代碼以輸出跟蹤信息,該信息告訴您的確切位置發生錯誤的位置。

其次,這裏不需要BinaryReaderBinaryWriter。你可以寫:

s.CopyTo(fs); 

這將複製整個流內容。