11 Kasım 2015 Çarşamba

How to create standalone executable file of Windows Forms Application project?

When you build a Windows Forms Application project, a single executable file and some other related files to be needed for the application are created in debug or release folder in the project directory. When you copy this executable file outside of the folder(debug/release) and run, you see that it does not work properly.

If you want to use a single executable file while running Windows Forms Application, all images and .dll files used in the application should be embedded into this executable file;

1) Images should be added into Resources;

2) Images should be configured as embedded resource in build action of properties of related image file;
3) .dll files should be added into Resources;
4) Some code should be added into Test.cs that contains Test.Designer.cs or any related C# file;
public Test()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}
5) Build your project! Executable file of your project is ready to be used independently. You can copy/paste and run it anywhere else. Well done!

References: 
* http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/

Hiç yorum yok:

Yorum Gönder