使用方法执行资源

使用方法执行资源

本文介绍了使用方法执行资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总而言之,我在工作项目中的逻辑是制作一个简单的程序,从我的源代码中启动文件,这可能类似于 setup.exe,但要避免出现文件夹中的文件(我想编译它或与我编码的程序合并(我的程序+外部文档在一起)

In a word my logic on my working project is to make a simple program that launches files out of my source code this could be anything like "setup.exe" but to avoid the case that the file from the folder(which is going to execute) is missing I want to compile it or merge with my program I coded (my program + outer documents together)

我可以在Compiled.exe文件中看到在debug文件夹中,它们中的2个已经合并在一起(当我在资源中添加程序时,由于文件较大,但我无法正确使用它)

I can see in the compiled.exe document in debug folder the 2 of them have been merged together ('cause of the bigger file size when I add the program in resources but i cannot use it properly)

我是在本例中尝试从资源中启动文件的是2.bat(批处理文件),但最初我想要一个.exe文件,但是我发现它真的很复杂,因为它看起来像20行代码,我无法清楚地了解发生了什么。
如果我被迫仅通过资源执行此操作,请使用以下资源位置作为示例 namespaceNAME.properties.resources.file

I am trying to launch a file from my resources in this example is 2.bat (batch file) but originally I want an .exe file BUT I found it really complicated as it looks like 20 lines of code that I cannot clearly understand what is going on.If I am forced to do it only via resources please make an example with the following resource location "namespaceNAME.properties.resources.file

记住,嵌入式资源是没有图像或.txt的可执行文件

编辑:

这是我到目前为止所做的:

This is what I have done so far :

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public class EmbeddedResourceFile : IDisposable
        {
            private readonly string _resourceName;
            private readonly Assembly _callingAssembly;

            public string FilePath { get; private set; }

            public EmbeddedResourceFile(string embeddedResourceName, string targetFilePath)
            {
                _resourceName = embeddedResourceName;
                FilePath = targetFilePath;
                _callingAssembly = Assembly.GetCallingAssembly();
                WriteFileToDisk();
            }

            private void WriteFileToDisk()
            {
                File.Delete(FilePath);
                var stream = _callingAssembly.GetManifestResourceStream(_resourceName);
                if (stream == null)
                {
                    throw new InvalidOperationException(string.Format("Embedded resource not found: {0}", _resourceName));
                }
                var fileStream = new FileStream(FilePath, FileMode.CreateNew);
                for (var i = 0; i < stream.Length; i++)
                {
                    fileStream.WriteByte((byte)stream.ReadByte());
                }
                fileStream.Close();
            }

            public void Dispose()
            {
                File.Delete(FilePath);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var exe =
            new EmbeddedResourceFile("test.Properties.Resources.ConsoleApplication",
                Path.Combine(Environment.CurrentDirectory, "cports.exe"));
            Process.Start(exe.FilePath);
        }
    }
}

当然,某事出了错,但我不知道

是什么,我认为我无缘无故地留下了许多无效的方法

Of course sth goes wrong but I don't know what
I think i have left many void methods untouched for no reason

我用

private void button1_Click(object sender, EventArgs e)
            {
                var exe =
                new EmbeddedResourceFile("test.Properties.Resources.ConsoleApplication.exe",
                    Path.Combine(Environment.CurrentDirectory, "ConsoleApplication.exe"));
                Process.Start(exe.FilePath);
            }

但出现类似出现

See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.

************** Exception Text **************
System.InvalidOperationException: Embedded resource not found: test.Properties.Resources.ConsoleApplication.exe
   at test.Form1.EmbeddedResourceFile.WriteFileToDisk() in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 50
   at test.Form1.EmbeddedResourceFile..ctor(String embeddedResourceName, String targetFilePath) in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 41
   at test.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\WindowsX\Desktop\Programms\MultiPackageInstaller\test\test\Form1.cs:line 68
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
test
    Assembly Version: 1.0.0.0
    Win32 Version: 1.0.0.0
    CodeBase: file:///C:/Users/WindowsX/Desktop/Programms/MultiPackageInstaller/test/test/bin/Debug/test.exe
----------------------------------------
System.Windows.Forms
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Configuration
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 4.0.0.0
    Win32 Version: 4.0.30319.34209 built by: FX452RTMGDR
    CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------

************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.

For example:



<configuration>
    <system.windows.forms jitDebugging="true" />
</configuration>

When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.

怎么可能找不到我单击测试项目>属性>资源>添加资源并打开文件

How is even possible not to be found I have clicked on my test project > properties > resources > add resource and opened the file

                            ****READ 'TILL THE END****


推荐答案

我编写了一个简单的EmbeddedResourceFile持久性对象,用于执行此类操作。

I wrote a simple EmbeddedResourceFile persistence object for doing things like this.

这将适用于属性设置为 Build Action-> Embedded Resource

This will work for included files whose properties are set to Build Action -> Embedded Resource

using System;
using System.IO;
using System.Reflection;

namespace EmbeddedResourceLauncherDemo
{
    public class EmbeddedResourceFile : IDisposable
    {
        private readonly string _resourceName;
        private readonly Assembly _callingAssembly;

        public string FilePath { get; private set; }

        public EmbeddedResourceFile(string embeddedResourceName, string targetFilePath)
        {
            _resourceName = embeddedResourceName;
            FilePath = targetFilePath;
            _callingAssembly = Assembly.GetCallingAssembly();
            WriteFileToDisk();
        }

        private void WriteFileToDisk()
        {
            File.Delete(FilePath);
            var stream = _callingAssembly.GetManifestResourceStream(_resourceName);
            if (stream == null)
            {
                throw new InvalidOperationException(string.Format("Embedded resource not found: {0}", _resourceName));
            }
            var fileStream = new FileStream(FilePath, FileMode.CreateNew);
            for (var i = 0; i < stream.Length; i++)
            {
                fileStream.WriteByte((byte)stream.ReadByte());
            }
            fileStream.Close();
        }

        public void Dispose()
        {
            File.Delete(FilePath);
        }
    }
}

然后您可以执行以下操作叫这个。确保确定您自己的清除所有持久文件的策略。

Then you can execute something by calling this. Be sure to figure out your own strategy for cleaning up any persisted files.

    [TestMethod]
    public void EmbeddedResourceFile_LaunchEmbeddedProgram()
    {
        var exe =
            new EmbeddedResourceFile("EmbeddedResourceLauncherDemo.ResourceApp.cports.exe",
                Path.Combine(Environment.CurrentDirectory, "cports.exe"));
        Process.Start(exe.FilePath);
    }

这篇关于使用方法执行资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:38