2012-06-14 115 views
0

我試過了幾種不同的方法,但保存時不會打開。我怎樣才能做到這一點?C#將MP4資源保存到文件

基本上我希望能夠將當前是資源文件的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(); 

       } 
      } 
     }} 
+2

什麼* *究竟是你想怎麼辦?你有什麼嘗試?發佈一些代碼... – tomfanning

+0

我試圖在axwindowsmediaplayer插件中播放資源視頻。 –

回答

1

你太過於複雜了。

嘗試類似這樣(注意,未編譯或測試,並且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可用,你需要自己實現一個,喜歡的其中之一:How do I copy the contents of one stream to another?

爲了得到當前程序集中的所有資源名稱的列表,請是這樣的:

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

採取什麼樣的控制檯上輪番上漲,並把它傳遞到GetManifestResourceStream()在第一個片段我張貼。

http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcenames.aspx

+0

你能給我一個資源名稱的例子嗎?我認爲這是我滑倒的地方。 –

+0

答覆已更新。 – tomfanning

+0

唯一可用的是..... Resources.resources –

0

爲什麼你寫的MP4作爲一個字符串?你應該寫出字節而不做修改。您轉換爲字符正在修改數據。使用FileStream調用並調用Write方法。

+0

這樣做更有意義。你可以簡單介紹一下如何在代碼的上下文中使用FileStream方法嗎? –

+0

使用File.Create打開FileStream並使用Stream.CopyTo方法將資源複製到FileStream。 – usr

+0

我感到很傻,但我仍然處於虧損狀態。 –

-1

你可以嘗試這樣的事:

我在粘貼錯誤的代碼....對不起,我很着急,

[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(); 
    } 

} 

這實際上加載視頻文件到一個目錄,但它應該適合你的格式。

-Thanks,

+0

呃?這沒有任何意義!與問題無關。 – tomfanning

+0

你的權利。我粘貼了錯誤的代碼:)我很着急....謝謝, – ironman