views:

159

answers:

2

how to download a video file .wmv and save it to the user's disk when click a button without using the browser save link as

+2  A: 

This is not that hard to do. As dtb mentions, the user's browser will still ask the user for permission to download the file, and they may have the option of choosing where to save the file. So it will not be completely automatic.

Here is a link to a blog post explaining how this is done using webforms. The main part you are interested in is this:

Response.ContentType = "video/x-ms-wmv";
Response.AppendHeader("Content-Disposition","attachment; filename=MyMovie.wmv");
Response.TransmitFile( Server.MapPath("~/videos/MyMovie.wmv") );
Response.End();

Here is a link stack overflow question which explains how to do it in MVC.

Based on your comment, you want to do this in silverlight. I'm not an expert in silverlight, but here is another question on stack overflow that discusses the issue.

magnifico
Isn't `Response.CacheControl = "No-Cache"` required? And what is the different between `WriteFile` and `TransmitFile` ?
abatishchev
@abatishchev: According to MSDN, "No-Cache" is the default. So, you don't need to set it. The difference between WriteFile and TransmitFile is that Transmit does not buffer the contents in memory. See: http://forums.asp.net/t/1513111.aspx
magnifico
But i wanna use it in silverlight application and there isn't system.web namespace so i can't use response how can i read it into byte[] ?? is that possible ?
MirooEgypt
+1  A: 

You can use the WebClient to download a wmv file and the SaveFileDialog to ask the user where to put it:-

void DownloadButton_Click(object sender, RoutedEventArgs e)
{
  var dialog = new SaveFileDialog();
  if (dialog.ShowDialog().Value)
  {
    var web = new WebClient();
    web.OpenReadCompleted = (s, args) =>
    {
      try
      {
        using (args.Result)
        using (Stream streamOut = args.UserState As Stream)
        {
          Pump(args.Result, streamOut);
        }
      }
      catch
      {
         // Do something sensible when the download has failed.
      }

    };
    web.OpenReadAsync(UriOfWmv,  ShowDialog.OpenFile()); 
  }
}

private static void Pump(Stream input, Stream output)
{
  byte[] bytes = new byte[4096];
  int n;

  while((n = input.Read(bytes, 0, bytes.Length)) != 0)
  {
    output.Write(bytes, 0, n);
  }
}

However currently there isn't a way to display download progress information. I was hoping that would get into the Silverlight 4 but as far as I can see it hasn't.

AnthonyWJones