How can I with button click export a file (file types: .jpg, .txt, .dll, ... etc) from my application resource code to a specific location on my computer (for example: C: \\ drive) I tried this code with button click: Main Code:
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ApplicationName.Files.name.dll");
FileStream fileStream = new FileStream("name.dll", FileMode.CreateNew);
for (int i = 0; i < stream.Length; i++)
fileStream.WriteByte((byte)stream.ReadByte());
fileStream.Close();
But the application stoped and show me this error: Error Message:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
stream was null.
More Informations:
1) I upload a .dll file to my resources.
2) I changed from this file Build Action to = "Embedded Resource".
I tried with Clint's help below. Images of my project now:
Scenario I (Your Scenario)
Scenario II
Usage
Important: Before using the Code
packages.config is an EmbeddedResource ( Substitute it with the resource you are using )
Namespace
of my project is ConsoleApp ( Substitute it with your namespace )
Main
static void Main(string[] args)
{
ResourceManager.GetResourceInfo("packages.config");
if (ResourceManager.resourceExists == false)
return;
//Loads packages.config in Bin/Debug
ResourceManager.LoadResource("packages.config");
}
ResourceManager.cs
class ResourceManager
{
public static bool resourceExists { get; set; } = false;
private static Stream resourceStream { get; set; }
public static void GetResourceInfo(string fileNameWithExtension)
{
//Substitut this with your Project Name
//Class Library Name AssistantLib > Resources > AssistantLib.dll
const string pathToResource = "ConsoleApp.Folder1.Folder2";
//The Dll that you want to Load
var assembly = Assembly.GetExecutingAssembly();
//var names = assembly.GetManifestResourceNames();
var stream = assembly.GetManifestResourceStream($"{pathToResource}.{fileNameWithExtension}");
if (stream == null)
return;
resourceExists = true;
resourceStream = stream;
}
public static void LoadResource(string newFileNameWithExtension)
{
if(File.Exists(newFileNameWithExtension))
{
Console.WriteLine("File already exists");
return;
}
using (Stream s = File.Create(newFileNameWithExtension))
{
Console.WriteLine("Loading file");
resourceStream.CopyTo(s);
}
}
}
Output
Package.Config in output folder
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.