Как вы пополняете байтовый массив с помощью SqlDataReader? - PullRequest
0 голосов
/ 01 февраля 2012

Это относится к: byte [] и эффективно проходит по ссылке

И SqlDataReader, найденные в этом посте: Получение двоичных данных с использованием SqlDataReader

Внутри цикла я вызываю базу данных и возвращаю большой объект (varbinary[max]).В настоящее время я сталкиваюсь с OutOfMemory исключениями, поэтому пытаюсь уменьшить занимаемую область в куче больших объектов (LOH).

Итак, я создаю байтовый массив для самого большого файла, которыйЯ бы скачал и добавил несколько отступов на всякий случай.Например:

byte[] currentFile = new byte[largestFileSize * 1.1];

Затем я передаю currentFile метод базы данных.В настоящее время мы используем EnterpriseLibrary для доступа к базе данных:

DbCommand storedProcedure = MedicareDatabase.Db.GetStoredProcCommand(spName);

storedProcedure.CommandTimeout = 5000;

if (parameters != null)
{
    foreach (Param parameter in parameters)
    {
        if (parameter != null)
        {
            MedicareDatabase.Db.AddInParameter(storedProcedure, parameter.ParameterName, parameter.DbType, parameter.Value);
        }
    }
}

try
{
    BinaryWriter bw;                        // Streams the BLOB to the FileStream object.

    int bufferSize = 100;                   // Size of the BLOB buffer.
    byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
    long retval;                            // The bytes returned from GetBytes.
    long startIndex = 0;                    // The starting position in the BLOB output.

    var myReader = MedicareDatabase.Db.ExecuteReader(storedProcedure);

    while (myReader.Read())
    {
        bw = new BinaryWriter();

        // Reset the starting byte for the new BLOB.
        startIndex = 0;

        // Read the bytes into outbyte[] and retain the number of bytes returned.
        retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

        // Continue reading and writing while there are bytes beyond the size of the buffer.
        while (retval == bufferSize)
        {
            bw.Write(outbyte);
            bw.Flush();

            // Reposition the start index to the end of the last buffer and fill the buffer.
            startIndex += bufferSize;
            retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
        }

        // Write the remaining buffer.
        bw.Write(outbyte, 0, (int)retval - 1);
        bw.Flush();

        // Close the output file.
        bw.Close();
    }

Это модификация кода, указанного во второй статье выше.

Вот мои вопросы (и не стесняйтесь поправлять меня, если я должен задавать разные вопросы)

  1. Как эффективно пополнить byte[], не создавая новыйobject?

  2. Приведенный выше код не использует CommandBehavior.SequentialAccess, который необходим также для того, чтобы не создавать новый объект.Как использовать EnterpriseLibrary с CommandBehavior s?

Я звоню в базу данных и возвращаю массив byte[]

Обновлено

Поэтому через некоторое время я решил вручную заполнить массив байтов.Ссылка теперь успешно передана.

        SqlConnection pubsConn = null;
        SqlCommand logoCMD = null;
        SqlDataReader myReader = null;

        try
        {
            pubsConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MedicareAccess"].ConnectionString);
            logoCMD = new SqlCommand("esMD.proc_WS_SelectBiztalkBinary", pubsConn);
            logoCMD.CommandType = CommandType.StoredProcedure;

            SqlParameter submissionSetParamter = logoCMD.Parameters.Add("@submissionSetId", SqlDbType.UniqueIdentifier);
            submissionSetParamter.Value = currentDocument.SubmissionSetId;

            SqlParameter fileNameParam = logoCMD.Parameters.Add("@fileName", SqlDbType.VarChar, 100);
            fileNameParam.Value = currentDocument.FullFileName;


            int bufferSize = 100;                   // Size of the BLOB buffer.
            byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
            long retval;                            // The bytes returned from GetBytes.
            long startIndex = 0;                    // The starting position in the BLOB output.

            // Open the connection and read data into the DataReader.
            pubsConn.Open();
            myReader = logoCMD.ExecuteReader(CommandBehavior.SequentialAccess);

            Array.Clear(data, 0, data.Length);

            if (myReader == null)
            {
                return;
            }

            while (myReader.Read())
            {
                currentDocument.Size = (int)myReader.GetBytes(0, 0, null, 0, 0);
                int locationCounter = 0;
                // Reset the starting byte for the new BLOB.
                startIndex = 0;

                // Read the bytes into outbyte[] and retain the number of bytes returned.
                retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);

                // Continue reading and writing while there are bytes beyond the size of the buffer.
                while (retval == bufferSize)
                {
                    for (int i = 0; i < retval; i++)
                    {
                        data[locationCounter] = outbyte[i];
                        locationCounter++;
                    }

                    // Reposition the start index to the end of the last buffer and fill the buffer.
                    startIndex += bufferSize;
                    retval = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (myReader != null)
            {
                myReader.Dispose();
                myReader.Close();
                myReader = null;
            }

            if (pubsConn != null)
            {
                pubsConn.Dispose();
                pubsConn.Close();
                pubsConn = null;
            }
        }

Я уверен, что есть более эффективный способ написать это.И не был полностью протестирован.Но ссылка наконец работает.

1 Ответ

0 голосов
/ 03 февраля 2012

Итак, я заменил основной цикл while следующим кодом:

            if (myReader.Read())
            {
                currentDocument.Size = myReader.GetBytes(0, 0, null, 0, 0);

                // Reset the starting byte for the new BLOB.
                long startIndex = 0;
                int bufferSize = 8196;                   // Size of the BLOB buffer.
                byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
                long bytesInBuffer = 0;                            // The bytes returned from GetBytes.

                // Continue reading and writing while there are bytes beyond the size of the buffer.
                while (startIndex < currentDocument.Size)
                {
                    bytesInBuffer = myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);
                    Array.Copy(outbyte, 0, currentDocument.Data, startIndex, bytesInBuffer);
                    startIndex += bytesInBuffer;
                }
            }

Работает сейчас.

...