In this post, I am going to show you how you can save an embedded resource as a file on disk. This is useful in certain scenarios. For example, I used this to save some background music onto the computer as the native MediaPlayer couldn’t use the application paths.
First things first, you want to make sure that you have set the Build Action to Embedded Resource in the properties for each of the items:
Once you have done that, we can go about creating a method to get the resource and save it to file. For me, that is as simple as:
public static void SaveMusicToDisk(){ //This creates a temp file in the %temp% directory called backgroundMusic.wav using (FileStream fileStream = File.Create(Path.GetTempPath() + "backgroundMusic.wav")){ //This looks into the assembly and gets the resource by name //For this to work, you need to use the full application path to the resource //You get this by using your project name following by the folder tree to your item Assembly.GetExecutingAssembly().GetManifestResourceStream("WPF.Assets.Sounds.backgroundmusic.wav").CopyTo(fileStream); } }
So that saves the file, what if I want to delete the file once the user wants to close the application?
For that I would use:
public static void DeleteMusicFromDisk(){ //This looks into the %temp% folder and deletes the file called "backgroundMusic.wav" File.Delete(Path.Combine(Path.GetTempPath(), "backgroundMusic.wav")); }
Peeeeerfect! 🎉 Does everything I need 😊
So, what if I wanted to save all the resources?
For that I could put all the resources into a string array and loop through them like this:
public static void SaveAllResources(){ //Gets all the resources associated with the assembly and puts them into an array string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames(); foreach (string resource in resources) { //Create a new file in the %temp% for each resource using (FileStream fileStream = File.Create(Path.GetTempPath() + resource)) { //Get the resource and save it to the current file Assembly.GetExecutingAssembly().GetManifestResourceStream(resource).CopyTo(fileStream); } } }
I hope you learn something or found this helpful. Enjoy!