Embed File in a Executable - c#

I'm trying to build a simple program and I want to find a way to embed a file (or multiple files) in the executable.
The program is very simple. I will be building a form using C# in visual studio. On the form, there will be couple questions and a submit button.
Once the user has answer all the questions and hit the submit button, if all answers are correct, I want to give the user the file as a prize. (The file can be image, video, or a zip file that contains multiple other files)
The way I want to give the user the file is very flexible. It can just be creating this file in the same directory as the executable, or given the download option for the user to save it somewhere else.
Below is the pseudo code
private void submit_Click(object sender, EventArgs e)
{
//functions to check all answers
if(all answers are correct)
{
label.Text = "Congrats! You answered all questions correctly";
//create the file that was embeded into the same directory as the executable
//let's call the file 'prize.img'
Process.Start("prize.img");
}
else
label.Text = "Some answers were not correct";
}
The logic is pretty simple and straight forward. The problem is, how can I embed "prize.img" into the executable? I will be giving this program (.exe) to a friend so he will not have any source and I can't guarantee the path.

You want to do embed the file as a resource.
Right-click the project file, select Properties.
In the window that opens, go to the Resources tab, and if it has just a blue link in the middle of the tab-page, click it, to create a new resource.
In your code you can type in Resources.TheNameYouGaveTheFileHere and you can access its contents. Note that the first time you use the Resources class in a class, you need to add a using directive (hit Ctrl+. after typing Resources to get the menu to get VS to do it for you).
Do you need help with the saving of the file also?
Edit:
You could do something like this:
var resource = Properties.Resources.yourResource;
FileStream fileStream = new FileStream("filename.exe", FileMode.CreateNew);
for (int i = 0; i < resource.Length; i++)
fileStream.WriteByte((byte)resource[i]);
fileStream.Close();
Does it help you?
EDIT:
As I can see you are getting a stream, here is an update to make it work:
var resource = Properties.Resources.yourResource;
FileStream fileStream = new FileStream("filename.exe", FileMode.CreateNew);
resource.CopyTo(fileStream);
fileStream.Close();
Does it work now?

Can't you add the image file as a resource in your solution? And then you can reference that resource in your code?
See if this may be what you're looking for:
Embedding Image Resource in Project
The link provided offers step-by-step how to accomplish this:
After adding the image as a resource, the instructions show how to access your image resource and use it in a program. Just click the link above and follow the instructions.
I followed the instructions above and wrote my program like this:
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var myAssembly = Assembly.GetExecutingAssembly();
var myStream = myAssembly.GetManifestResourceStream("WindowsFormsApplication6.Desert.jpg");
var image = new Bitmap(myStream);
pictureBox1.Image = image;
}
}
}
My output looks like this:
The image on the form came from the image that I embedded as a resource. Very easy to do.

Add the file into project then set its Build Action as Embeded resource.
From your code you can do something like this:
var _assembly = Assembly.GetExecutingAssembly();
var _stream = _assembly.GetManifestResourceStream("namespace.fileneme");

Related

Having permission issues when using itext7 to convert PNG files to PDFs, some commands seems to have access others dont

https://itextpdf.com/en/demos/convert-image-to-pdf-free-online
I got the demo code on how to do it from their site, I am building this in c# visual studio, with selenium/ nunit
It seems pretty straight forward, but im getting some issue that I dont understand. Here is my code:
using System;
using iText.IO.Image;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
namespace TesingPDFConvert
{
internal class Program
{
private static string ORIG = #"C:\Users\$username\Documents\c_projects\SeleniumScreenshots";
private static string OUTPUT_FOLDER = #"C:\Users\$username\Documents\c_projects\pdf_output\";
public static void Main(string[] args)
{
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(OUTPUT_FOLDER + "ImageToPdf.pdf"));
Document document = new Document(pdfDocument);
ImageData imageData = ImageDataFactory.Create(ORIG);
Image image = new Image(imageData);
image.SetWidth(pdfDocument.GetDefaultPageSize().GetWidth() - 50);
image.SetAutoScaleHeight(true);
document.Add(image);
pdfDocument.Close();
}
}
}
When I run this, I am getting access denied to the SeleniumScreenshots folder, but the other folder (pdf_output) seems to have access. If i change the folder to the pdf_output folder to get the images from there, im still getting access denied, however, it is writing the empty pdf to the output folder so it seems to have access. I tried changing the folders from "Read only" attribute but its not saving for some reason, I dont think thats the issue cause ive written to my documents folder in other selenium or c# projects and havent had issues. My thoughts are that im using itext7 wrong.
The goal here is to get grab the PNGs in my SeleniumScreenshots folder and turn them into a PDF and drop in the pdf_outputs folder after running a selenium/nunit test(not seen in code).
After not being able to get it to work with my selenium/nunit project, I opened a new project and set up their code to work(console application) and still had the same results. Im stumped.
I am pretty new to c# and visual studio code/developement in general. Thanks for any help in advance.
According to the comment, the solution is as follows:
ORIG is a file name at the end, you can’t refer to the folder.
OUTPUT_FOLDER last refers to the space under the folder, you are missing \.
There is no problem with the code itself.

c#/WinForms - Take file from resources and place it in directory on C: drive

I'm sure this has been done before and is probably quite simple to achieve but I can't seem to find anything on the internet when I've searched.
I'm looking for a way to pickup/copy a file from my applications resources and place it into a folder on my the C: drive. Can this be done? Or should I read in the contents of the file and then create a new one in the desired directory?Any pointers/advice would be appreciated! Thanks.
You can take the contents of the embedded file and write them out to your desired location as follows:
using (var fs = new FileStream(#"C:\Temp\Foo.txt", FileMode.Create))
using (var sw = new StreamWriter(fs))
{
var data = Stuff.Foo;
sw.Write(data);
}
I did this for a text file embedded in Stuff.resx in my project. There's a Write overload for various types so you can use what you need. For instance, an image will come back as a bitmap.
I achieved this by using File.WriteAllBytes()
Example:
File.WriteAllBytes("C:\\MyApp\\TextExample.json", MyApp.Properties.Resources.TextExample);

C# Awesomium Web Control - automatically download and open files

I currently have an Awesomium Webvcontrol in my WinForms application. When I click a download link it prompts with a save file dialog.
I need it to download the file to a preset location and automatically open it. I am using the latest version of Awesomium.
References:
using Awesomium.Windows.Forms;
using Awesomium.Core;
Has anyone an idea how to make the control point to a preset location?
I managed to figure a way around this.
I added an method to the download event of webcore.
Awesomium.Core.WebCore.Download += onDownload;
The method looks like this.
public static void onDownload(Object sender, DownloadEventArgs e)
{
e.Handled = true;
using (WebClient Client = new WebClient())
{
FileInfo file = new FileInfo("Your Path");
//replace Your Path with the path you wish to save the file including filename and extension
Client.DownloadFile(e.Url.ToString(), file.FullName);
//System.Windows.Forms.MessageBox.Show("Downloaded!");
Process.Start(file.FullName);
}
}
This now downloads and opens the file. In my case it was a .exe application.

Link to local text file in Solution c#

I need to save a set of 20 txt files into my solution so they will be included into the exe file. In such a way I will be able to send to the final users only the executable file and anything else.
I need to use the following function:
File.Copy( sourcePath, #path + "\\FileName.txt");
to copy one of the 20 files into another directory (according to the request of the user). In order to include the 20 txt files into the solution, I created a new folder into the Solution Explorer and I put them into it. Then I selected "Resources" into the option of the single txt file. Let's suppose the name of the folder is FOO and the file is NAME01, then I'm assuming the local address of the single txt file is "\FOO\NAME01.txt". But this is not working, I'm getting an arror from the File.Copy function related to the sourcePath.
Do you have any suggestions? I'm stacked on this problem and I cannot find any solution on the web. Many thanks!
Step 1: add the files to your project
Step 2: make them embedded resource
Step 3: export them to filesystem at runtime:
using System.Reflection;
namespace ConsoleApplication1
{
class Program4
{
public static void Main(string[] args)
{
using(var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("ConsoleApplication1.Files.TextFile1.txt"))
using (var filestream = System.IO.File.OpenWrite("target.txt"))
{
stream.CopyTo(filestream);
filestream.Flush();
filestream.Close();
stream.Close();
}
}
}
}
"ConsoleApplication1.Files.TextFile1.txt" comes from:
ConsoleApplication1: default namespace of the project containing the files
Files.TextFile1.txt: relative path, dotted, inside the dll (look # screenshot 1)

How to embed CHM file in application

Hey everyone,
I just finished up an application I've been working on for a while now. Probably the most complex one I've made to date. Due to this, I figured I'd go and make a help document to provide users with some info on it.
I've created a CHM file, and set up a helpProvider, however now my problem is how to include this and the HHC (Table of contents) file with my application. I feel like it'd be a pain to require the user to copy the two files themselves, so I'm trying to store them as embedded resources, then have the application write these out in the current directory.
Currently, this is the code I'm using:
var data = Properties.Resources.RERHelp;
using (var stream = new FileStream("RERHelp", FileMode.Create))
{
stream.Write(data, 0, data.Count() - 1);
stream.Flush();
}
helpProvider1.HelpNamespace = Directory.GetCurrentDirectory() + "\\RERHelp\\RERHelp.chm";
This works just fine, but it means I'd have to run through this twice, once with data set to Properties.Resources.RERHelp, and once for the Table of Contents file. Is there a better way to do this? Perhaps some way to embed the CHM and HHC files in the application, and access them without writing them to disk? If that isn't possible, which I'm thinking it isn't, is there a better way to go about it than how I am currently?
Thanks for any help!
Best Regards,
Ian
Apps usually use an installer, or zip archive of some sort. Both methods would allow a user to receive the application and the help files, without having to provide them separately.
Under your project properties - Resources, add a file resource ie:textmag.chm. I use filetype Text for the chm's
private void HelpToolStripMenuItem_Click(object sender, EventArgs e)
{
string helpFileName = "";
try
{
helpFileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources") + #"\TextMag.chm";
Help.ShowHelp(this, helpFileName);
}
catch (Exception ex)
{
string xxx = ex.Message;
}
}
Important: in the properties of the chm file under resources, the Build Action must be Content.
Oh, wow. Turns out I didn't need the HHC file as well. I assumed I did because when I'd open the help dialog, it would say that it couldn't find the table of contents.hhc file. I assumed for some reason it needed that in addition to the CHM. I originally just made a method to pass the resources to so as to prevent redundancy, and called that once for the CHM, and once for the HHC, but then I noticed this bit:
data.Count() - 1
I'm not sure why that - 1 was there, the solution I found had it, so I just left it there. When I removed that, the program ran, wrote out that file, and could then read it for the help documentation without the complaint of the missing HHC. All is well. Thanks for the suggestions, everyone!
So a solution is:
1) Copy your chm file to the required project folder
2) In your Visual C# solution explorer add existing item to the project (your chm file).
3) Select the Project menu then project properties.
4) Add existing resource.
5) Add the below code and connect to your help menu item.
private void WORKING_HELP()
{
string filePath = Directory.GetCurrentDirectory() + "\\BlitzHelp.chm";
try
{
//Check if already exists before making
if (!File.Exists(filePath))
{
var data = Properties.Resources.BlitzHelp;
using (var stream = new FileStream("BlitzHelp.chm", FileMode.Create))
{
stream.Write(data, 0, data.Count());
stream.Flush();
}
MessageBox.Show("file made");
}
}
catch
{
//May already be opened
}
Help.ShowHelp(this, filePath);
}

Categories