You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将视频文件嵌入C#生成的.exe文件并在程序中调用?

将视频嵌入C#可执行文件并播放的实现方法

一、将视频添加为嵌入资源

在Visual Studio中完成以下操作:

  • 把目标视频文件拖入项目(建议放在项目根目录的Resources文件夹下,方便管理)
  • 选中视频文件,在右侧属性面板设置:
    • 生成操作:改为嵌入的资源
    • 复制到输出目录:改为不复制

编译时视频会被直接打包进最终的.exe文件,无需额外携带外部文件。

二、从嵌入资源读取视频并生成临时文件

多数视频播放控件需要读取物理文件路径,无法直接播放内存流,因此需要先把嵌入的视频资源写入临时文件:

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

// 获取当前程序集
var assembly = Assembly.GetExecutingAssembly();
// 资源名称格式:项目命名空间.文件夹名.文件名(例如项目叫VideoEmbedDemo,视频在Resources下叫demo.mp4,资源名就是VideoEmbedDemo.Resources.demo.mp4)
string resourceName = "YourProjectNamespace.Resources.demo.mp4";

// 读取嵌入资源流
using (Stream resourceStream = assembly.GetManifestResourceStream(resourceName))
{
    if (resourceStream == null)
        throw new FileNotFoundException("未找到嵌入的视频资源", resourceName);

    // 创建带格式后缀的临时文件
    string tempFilePath = Path.Combine(Path.GetTempPath(), $"temp_video_{Guid.NewGuid()}.mp4");
    
    // 将资源流写入临时文件
    using (FileStream fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
    {
        resourceStream.CopyTo(fileStream);
    }

    // 此处tempFilePath即可传给播放器使用
}

三、播放临时文件

以WinForms为例,使用AxWindowsMediaPlayer控件实现播放:

  1. 右键工具箱→选择项→勾选Windows Media Player,将其添加到工具箱
  2. 拖一个AxWindowsMediaPlayer控件到窗体,命名为axWmp
  3. 在生成临时文件后,设置播放路径:
// 承接上一步的tempFilePath
axWmp.URL = tempFilePath;
axWmp.Ctlcontrols.play();

四、清理临时文件

程序退出时删除临时文件,避免磁盘占用:

// 在窗体的FormClosing事件中添加清理逻辑
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!string.IsNullOrEmpty(tempFilePath) && File.Exists(tempFilePath))
    {
        try
        {
            File.Delete(tempFilePath);
        }
        catch (Exception ex)
        {
            // 捕获异常防止程序退出失败(比如文件被播放器占用)
            Console.WriteLine($"删除临时文件失败:{ex.Message}");
        }
    }
}

常见问题说明

你之前尝试编译视频进exe没效果,大概率是这两个原因:

  • 未将视频文件的生成操作设置为嵌入的资源,导致视频未被打包进exe
  • 直接尝试用流播放,忽略了多数播放控件不支持流播放的限制,必须转成物理临时文件

内容的提问来源于stack exchange,提问作者Fariwar Farsian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:37:00