簡體   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