When I click on the button I get an error: Result: Stream was null (System.NullReferenceExceoption)
private void btScreenshot_Click(object sender, EventArgs e)
{
string exePath = "c:\\tmp\\adb.exe";
ExtractResource("Properties.Resources.AndroidBSPinstaller.adb.exe", exePath);
}
void ExtractResource(string resource, string path)
{
Stream stream = GetType().Assembly.GetManifestResourceStream(resource);
byte[] bytes = new byte[(int)stream.Length];
stream.Read(bytes, 0, bytes.Length);
File.WriteAllBytes(path, bytes);
}
CodePudding user response:
Here is a method to extract a file from resources
public static class ResourceExtensions
{
/// <summary>
/// Given a project resource extract to desired location
/// </summary>
/// <param name="BytesToWrite">Resource</param>
/// <param name="FileName">File name with extension and path is optional</param>
public static void FileSave(this byte[] BytesToWrite, string FileName)
{
if (File.Exists(FileName))
{
File.Delete(FileName);
}
var FileStream = new FileStream(FileName, FileMode.OpenOrCreate);
var BinaryWriter = new BinaryWriter(FileStream);
BinaryWriter.Write(BytesToWrite);
BinaryWriter.Close();
FileStream.Close();
}
}
Usage (path is in a TextBox but can easily be changed to any existing folder)
private void ExtractButton_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(FileNameTextBox.Text))
{
Resources.ColorCop.FileSave(FileNameTextBox.Text);
Process.Start(FileNameTextBox.Text);
}
}
Resource in project
Edit: changed to Embedded resource
NOTE: The full path will always begin with the default namespace.
For my app it's: read_stream_embedded_exe_onclick
.
Suggested workaround
Have you considered just setting the adb.exe file be a Copy to Output Directory
and calling Process.Start
to launch it? (Or if copying is the end goal, copy it to @"c:\tmp\adb.exe"
from there.)
CodePudding user response:
See picture fot the output. the file is copyd to "c:\tmp\adb.exe"