Reputation: 1139
I have embedded files in a program of mine previously with full success but I have now transferred the lines of code over to a second program and to my disappointment, I just cant get it to work for the life of me.
The code for the extraction is:
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));
}
To extract the program I want located in a folder named NewFolder1 I am typing the code:
Type myType = typeof(NewProgram);
var n = myType.Namespace.ToString();
String TempFileLoc = System.Environment.GetEnvironmentVariable("TEMP");
Extract(n, TempFileLoc, "NewFolder1", "Extract1.exe");
I can compile the program with no errors but once the program reaches the line to extract:
Extract(n, TempFileLoc, "NewFolder1", "Extract1.exe");
The program crashes and I get an error: "value cannot be null"
And YES I included System.IO & System.Reflection
Upvotes: 0
Views: 285
Reputation: 134125
A couple of things.
First, you probably should add some error checking so that you can figure out where things are failing. Rather than:
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." +
(internalFilePath== "" ? "" : internalFilePath + ".") + resourceName))
Write:
string name = nameSpace + "." +
(internalFilePath== "" ? "" : internalFilePath + ".") + resourceName;
Stream s = assembly.GetManifestResourceStream(name);
if (s == null)
{
throw new ApplicationException(); // or whatever
}
using (s)
{
// other stuff here
}
You should do the same thing when opening your FileStream
.
If you make those changes, you can single-step in the debugger or write code to output trace information that tells you exactly where the error is occurring.
Second, there's no need for the BinaryReader
or BinaryWriter
here. You can write:
s.CopyTo(fs);
Which will copy the entire stream contents.
Upvotes: 1