繁体   English   中英

C#将MP4资源保存到文件

[英]C# Saving an MP4 Resource to a file

我尝试了几种不同的方法,但是保存后无法打开。 我该怎么做?

基本上,我希望能够将当前是资源文件的MP4文件保存到可以作为路径访问的临时位置。

这是我尝试过的方法:

    public static void WriteResourceToFile(string resourceName, string fileName)
    {

        using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
        {

            if (s != null)
            {

                byte[] buffer = new byte[s.Length];

                char[] sb = new char[s.Length];

                s.Read(buffer, 0, (int)(s.Length));

                /* convert the byte into ASCII text */

                for (int i = 0; i <= buffer.Length - 1; i++)
                {

                    sb[i] = (char)buffer[i];

                }

                using (StreamWriter sw = new StreamWriter(fileName))
                {

                    sw.Write(sb);

                    sw.Flush();

                }
            }
        }}

您太复杂了。

尝试这样的操作(请注意,未经编译或测试,并且Stream.CopyTo()仅在.NET 4.0和更高版本中存在)。

using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)))
using (FileStream fs = File.Open("c:\myfile.mp4", FileMode.Create))
{
    s.CopyTo(fs);
}

任务完成。

如果没有可用的.NET 4.0,则需要自己实现,例如以下一种: 如何将一个流的内容复制到另一个?

要获取当前程序集中所有资源名称的列表,请执行以下操作:

Assembly a = Assembly.GetExecutingAssembly();
foreach (string s in a.GetManifestResourceNames())
{
    Console.WriteLine(s);
}
Console.ReadKey();

拿起控制台上显示的内容,并将其传递到我发布的第一个片段中的GetManifestResourceStream()中。

http://msdn.microsoft.com/zh-CN/library/system.reflection.assembly.getmanifestresourcenames.aspx

为什么要将MP4编写为字符串? 您应该写出未经修改的字节。 您转换为字符正在修改数据。 使用FileStream调用并调用Write方法。

您可以尝试这样的事情:

我粘贴了错误的代码。...对不起,我很着急

[HttpPost]
public ActionResult Create(VideoSermons video, HttpPostedFileBase videoFile)
{
    var videoDb = new VideoSermonDb();
    try
    {
        video.Path = Path.GetFileName(videoFile.FileName);
        video.UserId = HttpContext.User.Identity.Name;
        videoDb.Create(video);


        if (videoFile != null && videoFile.ContentLength > 0)
        {
            var videoName = Path.GetFileName(videoFile.FileName);
            var videoPath = Path.Combine(Server.MapPath("~/Videos/"),
                                         System.IO.Path.GetFileName(videoFile.FileName));
            videoFile.SaveAs(videoPath);

        }

        return RedirectToAction("Index");

    }
    catch
    {
        return View();
    }

}

这实际上将视频文件加载到目录中,但是它也应该适合您的格式。

-谢谢,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM