none
CSharp Reading File from FileStream to MemoryStream using Visual Studio 2008 SP1 RRS feed

  • Question

  • Dear All,

    I am looking for Reading File from FileStream to MemoryStream using Visual Studio 2008 SP1.

    So far, I could manage to find the code snippets below

    // in C#
    MemoryStream ms;
    string fileLocation;
    
    using (FileStream fileStream = File.OpenRead(fileLocation))
    {
        ms = new MemoryStream();
        ms.SetLength(fileStream.Length);
        fileStream.Read(ms.GetBuffer(), 0, (int)fileStream.Length);
    
        // in Java
         BufferedInputStream bis=new BufferedInputStream(new FileInputStream(filename));
    
          bis.mark(16384*1024);
    
        //in C#
        //MemoryStream bis = new MemoryStream(1024 * 1024);
    }
         
         byte[] bArr = new byte[1024];
         int    cnt=0;
         int    cnt1=0;
    
         do 
         {
           int cnt = bis.Read(bArr , 0, bArr .Length);   // got Data in here
           if (cnt> 0)
           {
    	    cnt += cnt1;
           }
         } while (cnt1 > 0);
    
         //bis.reset;    // in Java
    
         bArr = new byte[cnt];
    
         ms.Read(bArr,0,bArr.Length);  // There is no data in bArr after this line
    
         ms.Close();
    

    But all data is zero after this code line ms.Read(bArr,0,bArr.Length);  // There is no data in bArr after this line

    I hope someone will advise me to get it done.

    Thanks and best regards

    Monday, March 11, 2013 3:02 AM

Answers

  • MSDN has an example reading filestream to memory stream:

      MemoryStream destination = new MemoryStream();
      
      using (FileStream source = File.Open(@"c:\temp\data.dat",
          FileMode.Open))
      {
      
          Console.WriteLine("Source length: {0}", source.Length.ToString());
      
          // Copy source to destination.
      
          source.CopyTo(destination);
    

    I got this from the FileStream.CopyTo() method.
    Monday, March 11, 2013 5:35 AM