2010-04-12 7 views
17

Je dois créer un fichier zip contenant les documents qui existent sur le serveur. J'utilise la classe Package .Net pour le faire, et pour créer un nouveau paquet (qui est le fichier zip), je dois avoir un chemin vers un fichier physique ou un flux. J'essaye de ne pas créer un fichier réel qui serait le fichier zip, au lieu de créer simplement un flux qui existerait en mémoire ou quelque chose.Créer un flux sans avoir un fichier physique à créer à partir de

Ma question est de savoir comment instancier un nouveau flux (c'est-à-dire FileStream, MemoryStream, etc.) sans avoir de fichier physique à instancier.

Répondre

7

Il est un exemple de la façon de le faire sur le MSDN page for MemoryStream:

using System; 
using System.IO; 
using System.Text; 

class MemStream 
{ 
    static void Main() 
    { 
     int count; 
     byte[] byteArray; 
     char[] charArray; 
     UnicodeEncoding uniEncoding = new UnicodeEncoding(); 

     // Create the data to write to the stream. 
     byte[] firstString = uniEncoding.GetBytes(
      "Invalid file path characters are: "); 
     byte[] secondString = uniEncoding.GetBytes(
      Path.GetInvalidPathChars()); 

     using(MemoryStream memStream = new MemoryStream(100)) 
     { 
      // Write the first string to the stream. 
      memStream.Write(firstString, 0 , firstString.Length); 

      // Write the second string to the stream, byte by byte. 
      count = 0; 
      while(count < secondString.Length) 
      { 
       memStream.WriteByte(secondString[count++]); 
      } 

      // Write the stream properties to the console. 
      Console.WriteLine(
       "Capacity = {0}, Length = {1}, Position = {2}\n", 
       memStream.Capacity.ToString(), 
       memStream.Length.ToString(), 
       memStream.Position.ToString()); 

      // Set the position to the beginning of the stream. 
      memStream.Seek(0, SeekOrigin.Begin); 

      // Read the first 20 bytes from the stream. 
      byteArray = new byte[memStream.Length]; 
      count = memStream.Read(byteArray, 0, 20); 

      // Read the remaining bytes, byte by byte. 
      while(count < memStream.Length) 
      { 
       byteArray[count++] = 
        Convert.ToByte(memStream.ReadByte()); 
      } 

      // Decode the byte array into a char array 
      // and write it to the console. 
      charArray = new char[uniEncoding.GetCharCount(
       byteArray, 0, count)]; 
      uniEncoding.GetDecoder().GetChars(
       byteArray, 0, count, charArray, 0); 
      Console.WriteLine(charArray); 
     } 
    } 
} 

Est-ce ce que vous cherchez?

Questions connexes