当前位置: 首页>>代码示例>>C#>>正文


C# Stream.ToByteArray方法代码示例

本文整理汇总了C#中Stream.ToByteArray方法的典型用法代码示例。如果您正苦于以下问题:C# Stream.ToByteArray方法的具体用法?C# Stream.ToByteArray怎么用?C# Stream.ToByteArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Stream的用法示例。


在下文中一共展示了Stream.ToByteArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Parse

        //https://bitbucket.org/lorenzopolidori/http-form-parser/pull-requests
        private static NetHttpPostBody Parse(Stream stream, Encoding encoding, String FilePartName = null)
        {
            NetHttpPostBody postBody = new NetHttpPostBody() { ContentType = WebOperationContext.Current.IncomingRequest.ContentType };
            //postBody.Success = false;

            // Read the stream into a byte array
            byte[] data = stream.ToByteArray();

            // Copy to a string for header parsing
            string content = encoding.GetString(data);

            // The first line should contain the delimiter
            int delimiterEndIndex = content.IndexOf("\r\n");

            if (delimiterEndIndex > -1)
            {
                string delimiter = content.Substring(0, content.IndexOf("\r\n"));

                string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string s in sections)
                {
                    if (s.Contains("Content-Disposition"))
                    {
                        // If we find "Content-Disposition", this is a valid multi-part section
                        // Now, look for the "name" parameter
                        Match nameMatch = new Regex(@"(?<=name\=\"")(.*?)(?=\"")").Match(s);
                        string name = nameMatch.Value.Trim().ToLower();

                        if (name == FilePartName)
                        {
                            // Look for Content-Type
                            Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
                            Match contentTypeMatch = re.Match(content);

                            // Look for filename
                            re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
                            Match filenameMatch = re.Match(content);

                            // Did we find the required values?
                            if (contentTypeMatch.Success && filenameMatch.Success)
                            {
                                // Set properties
                                postBody.ContentType = contentTypeMatch.Value.Trim();
                                postBody.Filename = filenameMatch.Value.Trim();

                                // Get the start & end indexes of the file contents
                                int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;

                                byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
                                int endIndex = data.IndexOfArray(delimiterBytes, startIndex);//Misc.IndexOf(data, delimiterBytes, startIndex);

                                int contentLength = endIndex - startIndex;

                                // Extract the file contents from the byte array
                                byte[] fileData = new byte[contentLength];

                                Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);

                                postBody.FileContents = fileData;
                            }
                        }
                        else if (!string.IsNullOrEmpty(name.Trim()))
                        {
                            // Get the start & end indexes of the file contents
                            int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
                            postBody.Parameters.Add(name, s.Substring(startIndex).TrimEnd(new char[] { '\r', '\n' }).Trim());
                        }
                    }
                }

                // If some data has been successfully received, set success to true
                //if (postBody.FileContents != null || postBody.Parameters.Count != 0)
                //    postBody.Success = true;
            }
            return postBody;
        }
开发者ID:dialectsoftware,项目名称:DialectSoftware.Http,代码行数:78,代码来源:NetHttpUtility.cs

示例2: Put

 public void Put(Stream data, Uri path, bool overwrite = false, string userName = "", string password = "")
 {
     using (data)
     {
         File.WriteAllBytes(path.LocalPath, data.ToByteArray());
     }
 }
开发者ID:NatashaSchutte,项目名称:Warewolf-ESB,代码行数:7,代码来源:FileSystem.cs

示例3: Decode

		//new, it is stream parameter
		public static bool Decode (Stream buffer)
		{
			if (buffer == null)
				throw new Exception ();
			if (buffer.Length < sizeof(bool))
				throw new Exception ();
			return BitConverter.ToBoolean (buffer.ToByteArray (), 0);
		}
开发者ID:Egipto87,项目名称:DOOP.ec,代码行数:9,代码来源:BooleanEnconding.cs

示例4: Patch

        public static PatchResult Patch(Stream sourceStream, Stream patchStream, out MemoryStream modifyStream)
        {
            modifyStream = null;

            byte[] patchData = patchStream.ToByteArray();
            uint patchSize = (uint)patchData.Length;

            byte[] sourceData = sourceStream.ToByteArray();
            uint sourceSize = (uint)sourceData.Length;

            byte[] targetData = sourceData.ToList().ToArray();
            uint targetSize = (uint)targetData.Length;

            if (patchSize < 19)
                return PatchResult.patch_too_small;

            UInt32 modifyChecksum = 0xFFFFFFFF;
            UInt32 targetChecksum = 0xFFFFFFFF;
            uint modifyOffset = 0;
            uint sourceRelativeOffset = 0;
            uint targetRelativeOffset = 0;
            uint outputOffset = 0;

            re read = () =>
            {
                byte data = patchData[modifyOffset++];
                modifyChecksum = CRC32.Adjust(modifyChecksum, data);
                return data;
            };

            dec decode = () =>
            {
                UInt64 data = 0;
                UInt64 shift = 1;
                while (true)
                {
                    byte x = read();
                    data += (ulong)(x & 0x7f) * shift;
                    if ((x & 0x80) != 0)
                        break;
                    shift <<= 7;
                    data += shift;
                }
                return data;
            };

            wr write = (byte data) =>
            {
                targetData[outputOffset++] = data;
                targetChecksum = CRC32.Adjust(targetChecksum, data);
            };

            if (read() != 'B')
                return PatchResult.patch_invalid_header;
            if (read() != 'P')
                return PatchResult.patch_invalid_header;
            if (read() != 'S')
                return PatchResult.patch_invalid_header;
            if (read() != '1')
                return PatchResult.patch_invalid_header;

            uint modifySourceSize = (uint)decode();
            uint modifyTargetSize = (uint)decode();

            Array.Resize(ref targetData, (int)modifyTargetSize);
            targetSize = modifyTargetSize;

            uint modifyMarkupSize = (uint)decode();
            for (uint n = 0; n < modifyMarkupSize; n++)
                read();

            if (modifySourceSize > sourceSize)
                return PatchResult.source_too_small;
            if (modifyTargetSize > targetSize)
                return PatchResult.target_too_small;

            while (modifyOffset < patchSize - 12)
            {
                uint length = (uint)decode();
                Operation mode = (Operation)(length & 3);
                length = (length >> 2) + 1;

                switch (mode)
                {
                    case Operation.SourceRead:
                        while (length-- > 0)
                            write(sourceData[outputOffset]);
                        break;
                    case Operation.TargetRead:
                        while (length-- > 0)
                            write(read());
                        break;
                    case Operation.SourceCopy:
                    case Operation.TargetCopy:
                        int offset = (int)decode();
                        bool negative = (offset & 1) == 1;
                        offset >>= 1;
                        if (negative)
                            offset = -offset;

//.........这里部分代码省略.........
开发者ID:patrickb8man,项目名称:UTMM,代码行数:101,代码来源:BPSLinear.cs

示例5: Create

        public static bool Create(Stream sourceStream, Stream modifyStream, out MemoryStream patchStream, string metadata = "", UInt32 Granularity = 1)
        {
            MemoryStream patchFile = new MemoryStream();

            byte[] sourceData = sourceStream.ToByteArray();
            byte[] modifyData = modifyStream.ToByteArray();

            uint sourceSize = (uint)sourceData.Length;
            uint modifySize = (uint)modifyData.Length;

            UInt32 patchChecksum = 0xFFFFFFFF;
            uint targetRelativeOffset = 0;
            uint outputOffset = 0;

            wri write = (byte data) =>
            {
                patchFile.WriteByte(data);
                patchChecksum = CRC32.Adjust(patchChecksum, data);
            };

            enc encode = (UInt64 data) =>
            {
                while (true)
                {
                    byte x = (byte)(data & 0x7f);
                    data >>= 7;
                    if (data == 0)
                    {
                        write((byte)(0x80 | x));
                        break;
                    }
                    write(x);
                    data--;
                }
            };

            int targetReadLength = 0;

            flush targetReadFlush = () =>
            {
                if (targetReadLength != 0)
                {
                    encode((uint)Operation.TargetRead | (((uint)targetReadLength - 1) << 2));
                    int offset = (int)outputOffset - targetReadLength;
                    while (targetReadLength > 0)
                    {
                        write(modifyData[offset++]);
                        targetReadLength--;
                    }                         
                }
            };

            write((byte)'B');
            write((byte)'P');
            write((byte)'S');
            write((byte)'1');

            encode(sourceSize);
            encode(modifySize);

            uint markupSize = (uint)metadata.Length;
            encode(markupSize);
            for (int n = 0; n < markupSize; n++)
                write((byte)metadata[n]);

            while (outputOffset < modifySize)
            {
                uint sourceLength = 0;
                for (uint n = 0; outputOffset + n < Math.Min(sourceSize, modifySize); n++)
                {
                    if (sourceData[outputOffset + n] != modifyData[outputOffset + n])
                        break;
                    sourceLength++;
                }

                uint rleLength = 0;
                for (uint n = 1; outputOffset + n < modifySize; n++)
                {
                    if (modifyData[outputOffset] != modifyData[outputOffset + n])
                        break;
                    rleLength++;
                }

                if (rleLength >= 4)
                {
                    //write byte to repeat
                    targetReadLength++;
                    outputOffset++;
                    targetReadFlush();

                    //copy starting from repetition byte
                    encode((uint)Operation.TargetCopy | ((rleLength - 1) << 2));
                    uint relativeOffset = (outputOffset - 1) - targetRelativeOffset;
                    encode(relativeOffset << 1);
                    outputOffset += rleLength;
                    targetRelativeOffset = outputOffset - 1;
                }
                else if (sourceLength >= 4)
                {
                    targetReadFlush();
//.........这里部分代码省略.........
开发者ID:patrickb8man,项目名称:UTMM,代码行数:101,代码来源:BPSLinear.cs

示例6: GetMetadata

        public MetadataResult GetMetadata(Stream patchStream, out string metadataString)
        {
            metadataString = "";
            if (patchStream.Length < 19)
                return MetadataResult.patch_too_small;

            byte[] patchData = patchStream.ToByteArray();

            uint offset = 4;
            dec decode = () =>
            {
                UInt64 d = 0;
                UInt64 shift = 1;
                while (true)
                {
                    byte x = patchData[offset++];
                    d += ((ulong)(x & 0x7f) * shift);
                    if ((x & 0x80) != 0)
                        break;
                    shift <<= 7;
                    d += shift;
                }
                return d;
            };

            decode();
            decode();
            var modifyMarkupSize = (uint)decode();

            char[] buffer = new char[modifyMarkupSize + 1];
            for (int n = 0; n < modifyMarkupSize; n++)
                buffer[n] = (char)patchData[offset++];
            buffer[(int)modifyMarkupSize] = (char)0;
            metadataString = new string(buffer);

            return MetadataResult.success;
        }
开发者ID:patrickb8man,项目名称:UTMM,代码行数:37,代码来源:BPSLinear.cs

示例7: Compress

        /* Compress */
        public override MemoryStream Compress(ref Stream data, string filename)
        {
            try
            {
                uint DecompressedSize = (uint)data.Length;

                MemoryStream CompressedData = new MemoryStream();
                byte[] DecompressedData     = data.ToByteArray();

                uint SourcePointer = 0x0;
                uint DestPointer   = 0x4;

                // Test if the file is too large to be compressed
                if (data.Length > 0xFFFFFFFF)
                    throw new Exception("Input file is too large to compress.");

                // Set up the Lz Compression Dictionary
                LzWindowDictionary LzDictionary = new LzWindowDictionary();
                LzDictionary.SetWindowSize(0x1000);
                LzDictionary.SetMaxMatchAmount(0xFFFF + 273);

                // Figure out where we are going to write the decompressed file size
                if (data.Length <= 0xFFFFFF)
                    CompressedData.Write((uint)('\x11' | (DecompressedSize << 8)));
                else
                {
                    CompressedData.Write((uint)('\x11'));
                    CompressedData.Write(DecompressedSize);
                    DestPointer += 0x4;
                }

                // Start compression
                while (SourcePointer < DecompressedSize)
                {
                    byte Flag = 0x0;
                    uint FlagPosition = DestPointer;
                    CompressedData.WriteByte(Flag); // It will be filled in later
                    DestPointer++;

                    for (int i = 7; i >= 0; i--)
                    {
                        int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize);
                        if (LzSearchMatch[1] > 0) // There is a compression match
                        {
                            Flag |= (byte)(1 << i);

                            // Write the distance/length pair
                            if (LzSearchMatch[1] <= 0xF + 1) // 2 bytes
                            {
                                CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 1) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8)));
                                CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF));
                                DestPointer += 2;
                            }
                            else if (LzSearchMatch[1] <= 0xFF + 17) // 3 bytes
                            {
                                CompressedData.WriteByte((byte)(((LzSearchMatch[1] - 17) & 0xFF) >> 4));
                                CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 17) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8)));
                                CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF));
                                DestPointer += 3;
                            }
                            else // 4 bytes
                            {
                                CompressedData.WriteByte((byte)((1 << 4) | (((LzSearchMatch[1] - 273) & 0xFFFF) >> 12)));
                                CompressedData.WriteByte((byte)(((LzSearchMatch[1] - 273) & 0xFFF) >> 4));
                                CompressedData.WriteByte((byte)((((LzSearchMatch[1] - 273) & 0xF) << 4) | (((LzSearchMatch[0] - 1) & 0xFFF) >> 8)));
                                CompressedData.WriteByte((byte)((LzSearchMatch[0] - 1) & 0xFF));
                                DestPointer += 4;
                            }

                            LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]);
                            LzDictionary.SlideWindow(LzSearchMatch[1]);

                            SourcePointer += (uint)LzSearchMatch[1];
                        }
                        else // There wasn't a match
                        {
                            Flag |= (byte)(0 << i);

                            CompressedData.WriteByte(DecompressedData[SourcePointer]);

                            LzDictionary.AddEntry(DecompressedData, (int)SourcePointer);
                            LzDictionary.SlideWindow(1);

                            SourcePointer++;
                            DestPointer++;
                        }

                        // Check for out of bounds
                        if (SourcePointer >= DecompressedSize)
                            break;
                    }

                    // Write the flag.
                    // Note that the original position gets reset after writing.
                    CompressedData.Seek(FlagPosition, SeekOrigin.Begin);
                    CompressedData.WriteByte(Flag);
                    CompressedData.Seek(DestPointer, SeekOrigin.Begin);
                }

//.........这里部分代码省略.........
开发者ID:memerdot,项目名称:puyotools,代码行数:101,代码来源:onz.cs

示例8: UploadFile

        /// <summary>
        /// Envia um arquivo para o servidor a partir do conteudo e nome original, dando a opção de gravar no servidor com um novo nome
        /// </summary>
        /// <param name="binaryData">Dados do arquivo</param>
        /// <param name="originalFilename">Nome de origem</param>
        /// <param name="filename">Nome de destino</param>
        /// <returns>Id do arquivo gerado pelo índice</returns>
        public string UploadFile(Stream binaryData, string originalFilename, string filename)
        {
            string newFileName = NewFileName();
            string destFile = Path.Combine(_folderPath, newFileName); 
            string contentId = NextContentId();

            FileStream fs = File.Create(destFile, 2048, FileOptions.None);
            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(binaryData.ToByteArray());

            bw.Close();
            fs.Close();

            IncrementaIndice(contentId, newFileName);
            return contentId;
        }
开发者ID:rcarubbi,项目名称:Carubbi.Components,代码行数:24,代码来源:ContentManagerStub.cs

示例9: Compress

        /* Compress */
        public override MemoryStream Compress(ref Stream data, string filename)
        {
            try
            {
                uint DecompressedSize = (uint)data.Length;

                MemoryStream CompressedData = new MemoryStream();
                byte[] DecompressedData     = data.ToByteArray();

                uint SourcePointer = 0x0;
                uint DestPointer   = 0x10;

                // Test if the file is too large to be compressed
                if (data.Length > 0xFFFFFFFF)
                    throw new Exception("Input file is too large to compress.");

                // Set up the Lz Compression Dictionary
                LzBufferDictionary LzDictionary = new LzBufferDictionary();
                LzDictionary.SetBufferSize(0x1000);
                LzDictionary.SetBufferStart(0xFEE);
                LzDictionary.SetMaxMatchAmount(0xF + 3);

                // Start compression
                CompressedData.Write("LZ01");
                CompressedData.Write((uint)0); // Will be filled in later
                CompressedData.Write(DecompressedSize);
                CompressedData.Seek(4, SeekOrigin.Current); // Advance 4 bytes

                while (SourcePointer < DecompressedSize)
                {
                    byte Flag = 0x0;
                    uint FlagPosition = DestPointer;
                    CompressedData.WriteByte(Flag); // It will be filled in later
                    DestPointer++;

                    for (int i = 0; i < 8; i++)
                    {
                        int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize);
                        if (LzSearchMatch[1] > 0) // There is a compression match
                        {
                            Flag |= (byte)(0 << i);

                            CompressedData.WriteByte((byte)(LzSearchMatch[0] & 0xFF));
                            CompressedData.WriteByte((byte)(((LzSearchMatch[0] & 0xF00) >> 4) | ((LzSearchMatch[1] - 3) & 0xF)));

                            LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]);

                            SourcePointer += (uint)LzSearchMatch[1];
                            DestPointer   += 2;
                        }
                        else // There wasn't a match
                        {
                            Flag |= (byte)(1 << i);

                            CompressedData.WriteByte(DecompressedData[SourcePointer]);

                            LzDictionary.AddEntry(DecompressedData, (int)SourcePointer);

                            SourcePointer++;
                            DestPointer++;
                        }

                        // Check for out of bounds
                        if (SourcePointer >= DecompressedSize)
                            break;
                    }

                    // Write the flag.
                    // Note that the original position gets reset after writing.
                    CompressedData.Seek(FlagPosition, SeekOrigin.Begin);
                    CompressedData.WriteByte(Flag);
                    CompressedData.Seek(DestPointer, SeekOrigin.Begin);
                }

                CompressedData.Seek(0x4, SeekOrigin.Begin);
                CompressedData.Write((uint)CompressedData.Length);
                CompressedData.Seek(0, SeekOrigin.End);

                return CompressedData;
            }
            catch
            {
                return null; // An error occured while compressing
            }
        }
开发者ID:memerdot,项目名称:puyotools,代码行数:86,代码来源:lz01.cs

示例10: Compress

        /* Compress */
        public override MemoryStream Compress(ref Stream data, string filename)
        {
            try
            {
                uint DecompressedSize = (uint)data.Length;

                MemoryStream CompressedData = new MemoryStream();
                byte[] DecompressedData     = data.ToByteArray();

                uint SourcePointer = 0x0;
                uint DestPointer   = 0x40;

                uint MagicValue = (uint)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;

                // Test if the file is too large to be compressed
                if (data.Length > 0xFFFFFFFF)
                    throw new Exception("Input file is too large to compress.");

                // Set up the Lz Compression Dictionary
                LzBufferDictionary LzDictionary = new LzBufferDictionary();
                LzDictionary.SetBufferSize(0x1000);
                LzDictionary.SetBufferStart(0xFEE);
                LzDictionary.SetMaxMatchAmount(0xF + 3);

                // Start compression
                CompressedData.Write("LZ00");
                CompressedData.Write(0u); // Will be filled in later
                CompressedData.Seek(8, SeekOrigin.Current); // Advance 8 bytes

                // If the file extension is MRZ or TEZ, we probably want to change it
                if (Path.GetExtension(filename).ToLower() == ".mrz")
                    filename = Path.GetFileNameWithoutExtension(filename) + ".mrg";
                else if (Path.GetExtension(filename).ToLower() == ".tez")
                    filename = Path.GetFileNameWithoutExtension(filename) + ".tex";

                CompressedData.Write(filename, 31, 32, Encoding.GetEncoding("Shift_JIS"));
                CompressedData.Write(DecompressedSize);
                CompressedData.Write(MagicValue);
                CompressedData.Seek(8, SeekOrigin.Current); // Advance 8 bytes

                while (SourcePointer < DecompressedSize)
                {
                    MagicValue = GetNewMagicValue(MagicValue);

                    byte Flag = 0x0;
                    uint FlagPosition   = DestPointer;
                    uint FlagMagicValue = MagicValue; // Since it won't be filled in now
                    CompressedData.WriteByte(Flag); // It will be filled in later
                    DestPointer++;

                    for (int i = 0; i < 8; i++)
                    {
                        int[] LzSearchMatch = LzDictionary.Search(DecompressedData, SourcePointer, DecompressedSize);
                        if (LzSearchMatch[1] > 0) // There is a compression match
                        {
                            Flag |= (byte)(0 << i);

                            MagicValue = GetNewMagicValue(MagicValue);
                            CompressedData.WriteByte(EncryptByte((byte)(LzSearchMatch[0] & 0xFF), MagicValue));
                            MagicValue = GetNewMagicValue(MagicValue);
                            CompressedData.WriteByte(EncryptByte((byte)(((LzSearchMatch[0] & 0xF00) >> 4) | ((LzSearchMatch[1] - 3) & 0xF)), MagicValue));

                            LzDictionary.AddEntryRange(DecompressedData, (int)SourcePointer, LzSearchMatch[1]);

                            SourcePointer += (uint)LzSearchMatch[1];
                            DestPointer   += 2;
                        }
                        else // There wasn't a match
                        {
                            Flag |= (byte)(1 << i);

                            MagicValue = GetNewMagicValue(MagicValue);
                            CompressedData.WriteByte(EncryptByte(DecompressedData[SourcePointer], MagicValue));

                            LzDictionary.AddEntry(DecompressedData, (int)SourcePointer);

                            SourcePointer++;
                            DestPointer++;
                        }

                        // Check for out of bounds
                        if (SourcePointer >= DecompressedSize)
                            break;
                    }

                    // Write the flag.
                    // Note that the original position gets reset after writing.
                    CompressedData.Seek(FlagPosition, SeekOrigin.Begin);
                    CompressedData.WriteByte(EncryptByte(Flag, FlagMagicValue));
                    CompressedData.Seek(DestPointer, SeekOrigin.Begin);
                }

                CompressedData.Seek(0x4, SeekOrigin.Begin);
                CompressedData.Write((uint)CompressedData.Length);
                CompressedData.Seek(0, SeekOrigin.End);

                return CompressedData;
            }
            catch
//.........这里部分代码省略.........
开发者ID:memerdot,项目名称:puyotools,代码行数:101,代码来源:lz00.cs

示例11: UploadFile

        /// <summary>
        /// Envia um arquivo para o servidor a partir do conteudo e nome original, dando a opção de gravar no servidor com um novo nome
        /// </summary>
        /// <param name="binaryData">Dados do arquivo</param>
        /// <param name="originalFilename">Nome de origem</param>
        /// <param name="filename">Nome de destino</param>
        /// <returns>Id do arquivo gerado pelo content manager</returns>
        public string UploadFile(Stream binaryData, string originalFilename, string filename)
        {
            // Cria uma nova instancia do WebServices 
            IR4CorrespProxy content = new IR4CorrespProxy();

            content.RequireMtom = true;

            // Aponta a instancia atual do WebService para a URL de desenvolvimento: 
            content.Url = _url; //"http://cmdes.itau/CMBSpecificWebService/services/CMWebService";

            // Aponta a instancia atual do WebService para a URL de produção: 
            //content.Url = http://cmcorp2.itau/CMBSpecificWebService/services/CMWebService"; 
            // Cria uma requisição de Criação de Item "CreateItemRequest" 
            CreateItemRequest Request = new CreateItemRequest();
            // Autenticação 
            Request.AuthenticationData = new AuthenticationData();
            Request.AuthenticationData.ServerDef = new ServerDef();
            //Request.AuthenticationData.ServerDef.ServerName = "NLSDB01"; // PRODUCAO 
            Request.AuthenticationData.ServerDef.ServerName = _serverName;// "NLSDBDES";  // DESENVOLVIMENTO 
            Request.AuthenticationData.ServerDef.ServerType = ServerType.ICM;
            Request.AuthenticationData.LoginData = new AuthenticationDataLoginData();
            Request.AuthenticationData.LoginData.UserID = _username;// "USUARIO";
            Request.AuthenticationData.LoginData.Password = _password;// "SENHA";
            // Cria um novo Item de requisição 
            // Isto é necessário pois esta propriedade não é automaticamente criada pelo 
            //"CreateItemRequest" 
            Request.Item = new CreateItemRequestItem();

            // Cria um novo Item de XML 
            Request.Item.ItemXML = new ItemXML();

            // Associa o item ao OA0_ExemploCM 
            Request.Item.ItemXML.IR4_CORRESP = new IR4_CORRESP();
            // Atribui as propriedades do arquivo nos campos do OA0_ExemploCM. 
            //Request.Item.ItemXML.IR4_CORRESP.IR4_COD_CORRESP = "Titulo de Teste"; 

            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT = new ICMBASETEXT[1];
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0] = new ICMBASETEXT();
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject = new LobObjectType();
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.label = new LobObjectTypeLabel();
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.label.name = filename;
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.originalFileName = originalFilename;
            Request.Item.ItemXML.IR4_CORRESP.ICMBASETEXT[0].resourceObject.MIMEType = Path.GetExtension(originalFilename).GetMimeType();


            // Definições do arquivo que será incluído 
            MTOMAttachment[] attachments = new MTOMAttachment[1];
            attachments[0] = new MTOMAttachment();
            attachments[0].ID = originalFilename;
            attachments[0].MimeType = Path.GetExtension(originalFilename).GetMimeType();
            attachments[0].Value = binaryData.ToByteArray();

            Request.mtomRef = new MTOMAttachment[1];
            Request.mtomRef[0] = attachments[0];

            // Realiza a chamada da requisição de novo item, e retorna um "Reply", contendo  
            // informações sobre a situação da requisição. 
            CreateItemReply reply = content.CreateItem(Request);

            if (reply.RequestStatus.success)
            {
                //Console.WriteLine("Arquivo criado com sucesso: " + reply.Item.URI); 
                Uri uri = new Uri(reply.Item.URI);

                HttpRequest req = new HttpRequest(null, uri.ToString(), uri.Query.Substring(1)); // uri.Query inclui o '?', o que o HttpRequest não espera

                return req.Params["pid"];
            }
            else
            {
                //Console.WriteLine("Falha ao criar arquivo"); 
                ErrorData[] err = reply.RequestStatus.ErrorData;
                string errorStack = "";
                for (int i = 0; i < err.Length; i++)
                {
                    errorStack += "Item: " + err[i].Item + " Code: " + err[i].returnCode + "Stack: " + err[i].stackTrace + "\n";
                }
                throw new Exception(errorStack);
            }
        }
开发者ID:rcarubbi,项目名称:Carubbi.Components,代码行数:87,代码来源:ContentManagerIR4Corresp.cs

示例12: Check

 // See if the texture is a Pvr
 public override bool Check(ref Stream input, string filename)
 {
     try   { return PvrTexture.IsPvrTexture(input.ToByteArray()); }
     catch { return false; }
 }
开发者ID:memerdot,项目名称:puyotools,代码行数:6,代码来源:pvr.cs

示例13: WriteToFtp

        int WriteToFtp(Stream src, IActivityIOPath dst)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(dst.Path));
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.KeepAlive = false;
            request.EnableSsl = EnableSsl(dst);

            if(dst.Username != string.Empty)
            {
                request.Credentials = new NetworkCredential(dst.Username, dst.Password);
            }

            if(dst.IsNotCertVerifiable)
            {
                ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
            }

            request.ContentLength = src.Length;
            using(Stream requestStream = request.GetRequestStream())
            {
                using(src)
                {
                    byte[] payload = src.ToByteArray();
                    int writeLen = payload.Length;
                    requestStream.Write(payload, 0, writeLen);
                }
            }

            var result = (int)request.ContentLength;

            using(var response = (FtpWebResponse)request.GetResponse())
            {
                if(response.StatusCode != FtpStatusCode.FileActionOK && response.StatusCode != FtpStatusCode.ClosingData)
                {
                    throw new Exception("File was not created");
                }
            }
            return result;
        }
开发者ID:FerdinandOlivier,项目名称:Warewolf-ESB,代码行数:40,代码来源:Dev2FTPProvider.cs

示例14: Decrypt

 public byte[] Decrypt(Stream stream, byte[] key = null)
 {
     return Decrypt(stream.ToByteArray(), key);
 }
开发者ID:lruckman,项目名称:DRS,代码行数:4,代码来源:FileEncryptor.cs

示例15: Put

        public int Put(Stream src, IActivityIOPath dst, Dev2CRUDOperationTO args, string whereToPut, List<string> filesToCleanup)
        {
            int result = -1;
            using (src)
            {
                //2013.05.29: Ashley Lewis for bug 9507 - default destination to source directory when destination is left blank or if it is not a rooted path
                if (!Path.IsPathRooted(dst.Path))
                {
                    //get just the directory path to put into
                    if (whereToPut != null)
                    {
                        //Make the destination directory equal to that directory
                        dst = ActivityIOFactory.CreatePathFromString(whereToPut + "\\" + dst.Path, dst.Username, dst.Password,dst.PrivateKeyFile);
                    }
                }
                if (args.Overwrite || !args.Overwrite && !FileExist(dst))
                {
                    _fileLock.EnterWriteLock();
                    try
                    {
                        if (!RequiresAuth(dst))
                        {
                            using (src)
                            {
                                File.WriteAllBytes(dst.Path, src.ToByteArray());
                                result = (int)src.Length;
                            }
                        }
                        else
                        {
                            // handle UNC path
                            SafeTokenHandle safeTokenHandle;
                            bool loginOk = LogonUser(ExtractUserName(dst), ExtractDomain(dst), dst.Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);


                            if (loginOk)
                            {
                                using (safeTokenHandle)
                                {

                                    WindowsIdentity newID = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
                                    using (WindowsImpersonationContext impersonatedUser = newID.Impersonate())
                                    {
                                        // Do the operation here
                                        using (src)
                                        {
                                            File.WriteAllBytes(dst.Path, src.ToByteArray());
                                            result = (int)src.Length;
                                        }

                                        // remove impersonation now
                                        impersonatedUser.Undo();
                                    }
                                }
                            }
                            else
                            {
                                // login failed
                                throw new Exception("Failed to authenticate with user [ " + dst.Username + " ] for resource [ " + dst.Path + " ] ");
                            }
                        }
                    }
                    finally
                    {
                        _fileLock.ExitWriteLock();
                    }
                }
            }
            return result;
        }
开发者ID:Robin--,项目名称:Warewolf,代码行数:70,代码来源:Dev2FileSystemProvider.cs


注:本文中的Stream.ToByteArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。