21

サーバー上に存在するドキュメントを含む zip ファイルを作成する必要があります。そのために .Net Package クラスを使用しています。新しいパッケージ (zip ファイル) を作成するには、物理​​ファイルまたはストリームへのパスが必要です。zipファイルになる実際のファイルを作成するのではなく、メモリなどに存在するストリームを作成しようとしています。

私の質問は、インスタンス化する物理ファイルがなくても、新しいストリーム (つまり、FileStream、MemoryStream など) をインスタンス化する方法です。

4

3 に答える 3

32

MemoryStreamにはいくつかのコンストラクター オーバーロードがあり、いずれもファイルを必要としません。

于 2010-04-12T15:07:46.200 に答える
10

MemoryStreamの MSDN ページでこれを行う方法の例があります。

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

これはあなたが探しているものですか?

于 2010-04-12T15:13:00.693 に答える
3

新しいストリームを作成して書き込むことができます。オブジェクトを構築するためのファイルは必要ありません。

http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx

書き込み方法:

http://msdn.microsoft.com/en-us/library/system.io.memorystream.write.aspx

メモリ ストリームのコンストラクタ:

http://msdn.microsoft.com/en-us/library/system.io.memorystream.memorystream.aspx

于 2010-04-12T15:08:47.867 に答える