2013-07-19 63 views
0

嵌入的資源在這裏的想法是從嵌入式資源的批處理文件解壓到C盤上的臨時目錄,然後提取該批處理文件運行。我遇到的問題是「對象引用未設置爲對象實例」的錯誤。有問題提取C#應用程序

的代碼是:

public static void ExtractResource() 
    { 
     using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(Namespace.Properties.Resources.Backup)) 
     { 
      byte[] buffer = new byte[s.Length]; 
      s.Read(buffer, 0, buffer.Length); 
      using (var sw = new BinaryWriter(File.Open(@"C:\test.bat", FileMode.OpenOrCreate))) 
      { 
       sw.Write(buffer); 
      } 
     } 
    } 

在此行中出現的錯誤:

byte[] buffer = new byte[s.Length]; 
+0

根據[doco](http://msdn.microsoft.com/en-us/library/5kx66y1a.aspx)。清單資源;如果在編譯期間沒有指定資源,或者資源對調用者不可見,則爲null。 –

+0

@darkstarohio對這些建議的反饋是什麼? –

回答

1

如果你嵌入的資源,然後將生成靜態方法來獲取嵌入的文件內容的內容,在內部它請撥打ResourceManager.GetString方法,所以請嘗試以下方法

using (var sw = new BinaryWriter(File.Open(@"C:\test.bat", FileMode.OpenOrCreate))) 
{ 
    writer.Write(Namespace.Properties.Resources.Backup); 
} 
+0

非常感謝。這個工作的例子。測試。 –

0

爲你工作?

public static class Program 
     { 
      public static void Main() 
      { 
       ExtractResource(); 
      } 

      public static void ExtractResource() 
      { 
       //replace your embedded file by yours 
       using (var inputStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.XMLFile1.xml")) 
       { 
        using(var outputStream = File.Create(@"D:\test.bat")) 
        { 
         /// fix your buffer size 8192,4096 etc. 
         var buffer = new byte[8192]; 

         int numberOfBytesRead; 
         while (inputStream != null && (numberOfBytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) 
         { 
          outputStream.Write(buffer, 0, numberOfBytesread); 
         } 
        } 
       } 

      } 
     } 
0

這聽起來像流不返回或它不報告長度。

而且,不看整個的流一次,它不是很高效存儲,而不是當你開始使用它實際上可能沒有報告其實際長度的網絡流或大文件遵循的最佳模式。

public void WriteResrouce(string resourcePath, string targetPath) 
{ 
    var buffer = new byte[64 * 1024]; //i've picked 64k as a reasonable sized block 
    using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath)) 
    using (var sw = new BinaryWriter(File.Open(targetPath, FileMode.OpenOrCreate))) 
    { 
     var readCount = -1; 
     while (0 < (readCount = s.Read(buffer, 0, buffer.Length))) 
     { 
      sw.Write(buffer, 0, readCount); 
     } 
    } 
}