Saving from a Stream to a File

Hi,This code can be used to save a current Stream to a File on your machine.
The Stream may be an embeded resource i.e an avi  clip stored in a dll or an exe  & you wanna retrive ,capture  & save it  to be played with media player because mp can only play files(i.e path & extention)& cann,t play a stream 

 using the code

it is a class that must be used with a win Application

if u wanna use your own gif which is stored in the dll  
 

 1//load the assembly
 2   //SourceDLL = i.e exe or dll path 
 3   Assembly myAessembly = Assembly.LoadFrom(SourceDLL);
 4       
 5   
 6         //load the spacific embeded file 
 7            //i.e jpg , mp3,avi,tect 
 8   Stream myStream =           //"namespac.filename.extention"
 9    myAessembly.GetManifestResourceStream(sourceNamespace);
10
11               //now myStream is a stream contaning the avi
12

 pictureBox1 can recive the stream

pictureBox1.Image=Image.FromStream(myStream);

  what if that embeded resource is mp3 not an image?

i.e unlick pictureBox1 media player accept file path to play

& not a stream , so save the stream to your local disk   

  

 1public void Copying(Stream FromStream,string TargetFile){
 2         
 3
 4
 5                  // FromStream=the stream we wanna save to a file 
 6                   //TargetFile = name&path of file to be created to save to 
 7                   //i.e"c:\mysong.mp3" 
 8         
 9  
10   try
11   {
12    //Creat a file to save to
13
14    Stream ToStream = File.Create(TargetFile);
15
16    //use the binary reader & writer because
17    //they can work with all formats
18    //i.e images, text files ,avi,mp3..
19
20    
21
22    BinaryReader br = new BinaryReader(FromStream);
23    
24    
25    BinaryWriter bw = new BinaryWriter(ToStream);
26
27
28                //copy data from the FromStream to the outStream
29    //convert from long to int 
30    bw.Write(br.ReadBytes((int)FromStream.Length));
31    //save
32    bw.Flush();
33    //clean up 
34    bw.Close();
35    br.Close();
36   }

37
38    //use Exception e as it can handle any exception 
39   catch(Exception e)
40   {
41    //code if u like 
42   }

43  }

44
45

I hope u enjoy this code

thanks

posted on 2006-11-23 11:33  jtech  阅读(598)  评论(1)    收藏  举报