Read() public abstract method

public abstract Read ( [ buffer, int offset, int count ) : int
buffer [
offset int
count int
return int
Esempio n. 1
0
		public OggTag Read( Stream oggStream )
		{
			OggTag tag = new OggTag();
			
			byte[] b = new byte[4];
			oggStream.Read( b , 0,  b .Length);
			int vendorstringLength = Utils.GetNumber( b, 0, 3);
			b = new byte[vendorstringLength];
			oggStream.Read( b , 0,  b .Length);
			tag.Add("vendor", new string(Encoding.UTF8.GetChars(b)));
			
			b = new byte[4];
			oggStream.Read( b , 0,  b .Length);
			int userComments = Utils.GetNumber( b, 0, 3);

			for ( int i = 0; i < userComments; i++ ) {
				b = new byte[4];
				oggStream.Read( b , 0,  b .Length);
				int commentLength = Utils.GetNumber( b, 0, 3);

				b = new byte[commentLength];
				oggStream.Read( b , 0,  b .Length);
				tag.AddOggField(b);
			}
			
			return tag;
		}
Esempio n. 2
0
		public void Write(Tag tag, Stream apeStream, Stream tempStream) {
			ByteBuffer tagBuffer = tc.Create(tag);

			if (!TagExists(apeStream)) {
				apeStream.Seek(0, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
			} else {
				apeStream.Seek( -32 + 8 , SeekOrigin.End);
			
				//Version
				byte[] b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				int version = Utils.GetNumber(b, 0, 3);
				if(version != 2000) {
					throw new CannotWriteException("APE Tag other than version 2.0 are not supported");
				}
				
				//Size
				b = new byte[4];
				apeStream.Read( b , 0,  b.Length);
				long oldSize = Utils.GetLongNumber(b, 0, 3) + 32;
				int tagSize = tagBuffer.Capacity;
				
				apeStream.Seek(-oldSize, SeekOrigin.End);
				apeStream.Write(tagBuffer.Data, 0, tagBuffer.Capacity);
					
				if(oldSize > tagSize) {
					//Truncate the file
					apeStream.SetLength(apeStream.Length - (oldSize-tagSize));
				}
			}
		}
Esempio n. 3
0
        public static void ReadBody(Stream inputStream, Stream output, Headers headers, bool strict, ref float progress)
        {
            // Read Body
            byte[] buffer = new byte[8192];
            int contentLength = 0;

            if (int.TryParse (headers.Get ("Content-Length"), out contentLength)) {
                if (contentLength > 0) {
                    var remaining = contentLength;
                    while (remaining > 0) {
                        var count = inputStream.Read (buffer, 0, buffer.Length);
                        if (count == 0) {
                            break;
                        }
                        remaining -= count;
                        output.Write (buffer, 0, count);
                        progress = Mathf.Clamp01 (1.0f - ((float)remaining / (float)contentLength));
                    }
                }
            } else {
                if (!strict) {
                    var count = inputStream.Read (buffer, 0, buffer.Length);
                    while (count > 0) {
                        output.Write (buffer, 0, count);
                        count = inputStream.Read (buffer, 0, buffer.Length);
                    }
                }
                progress = 1;
            }
        }
Esempio n. 4
0
		public bool Read(Id3Tag tag, Stream mp3Stream)
		{
			//Check wether the file contains an Id3v1 tag--------------------------------
			mp3Stream.Seek( -128 , SeekOrigin.End);
			
			byte[] b = new byte[3];
			mp3Stream.Read( b, 0, 3 );
			mp3Stream.Seek(0, SeekOrigin.Begin);
			string tagS = Encoding.ASCII.GetString(b);
			if(tagS != "TAG")
				return false;
			
			mp3Stream.Seek( - 128 + 3, SeekOrigin.End );
			//Parse the tag -)------------------------------------------------
			tag.AddTitle(Read(mp3Stream, 30));
			tag.AddArtist(Read(mp3Stream, 30));
			tag.AddAlbum(Read(mp3Stream, 30));
			//------------------------------------------------
			tag.AddYear(Read(mp3Stream, 4));
			tag.AddComment(Read(mp3Stream, 30));

			//string trackNumber;
			mp3Stream.Seek(- 2, SeekOrigin.Current);
			b = new byte[2];
			mp3Stream.Read(b, 0, 2);
			
			if (b[0] == 0)
				tag.AddTrack(b[1].ToString());

			byte genreByte = (byte) mp3Stream.ReadByte();
			mp3Stream.Seek(0, SeekOrigin.Begin);
			tag.AddGenre(TagGenres.Get(genreByte));

			return true;
		}
Esempio n. 5
0
        /// <summary>
        /// Inflate the token
        /// NOTE: This operation is not continuable and assumes that the entire token is available in the stream
        /// </summary>
        /// <param name="source">Stream to inflate the token from.</param>
        /// <returns>True in case of success, false otherwise.</returns>
        public override bool Inflate(Stream source)
        {
            // Read length of entire message
            uint totalLengthOfData = TDSUtilities.ReadUInt(source);

            // Read length of the fedauth token
            uint tokenLength = TDSUtilities.ReadUInt(source);

            // Read the fedauth token
            _token = new byte[tokenLength];
            source.Read(_token, 0, (int)tokenLength);

            // Read nonce if it exists
            if (totalLengthOfData > tokenLength)
            {
                _nonce = new byte[totalLengthOfData - tokenLength];
                source.Read(_nonce, 0, (int)(totalLengthOfData - tokenLength));
            }
            else if (tokenLength > totalLengthOfData)
            {
                // token length cannot be greater than the total length of the message
                return false;
            }

            return true;
        }
        public EncodingInfo Read( Stream raf )
        {
            EncodingInfo info = new EncodingInfo();

            //Begin info fetch-------------------------------------------
            if ( raf.Length == 0 ) {
                //Empty File
                throw new CannotReadException("File is empty");
            }
            raf.Seek( 0 , SeekOrigin.Begin);

            //MP+ Header string
            byte[] b = new byte[4];
            raf.Read(b, 0, b.Length);
            string mpc = new string(System.Text.Encoding.ASCII.GetChars(b));
            if (mpc != "MAC ") {
                throw new CannotReadException("'MAC ' Header not found");
            }

            b = new byte[4];
            raf.Read(b, 0, b.Length);
            int version = Utils.GetNumber(b, 0,3);
            if(version < 3970)
                throw new CannotReadException("Monkey Audio version <= 3.97 is not supported");

            b = new byte[44];
            raf.Read(b, 0, b.Length);
            MonkeyDescriptor md = new MonkeyDescriptor(b);

            b = new byte[24];
            raf.Read(b, 0, b.Length);
            MonkeyHeader mh = new MonkeyHeader(b);

            raf.Seek(md.RiffWavOffset, SeekOrigin.Begin);
            b = new byte[12];
            raf.Read(b, 0, b.Length);
            WavRIFFHeader wrh = new WavRIFFHeader(b);
            if(!wrh.Valid)
                throw new CannotReadException("No valid RIFF Header found");

            b = new byte[24];
            raf.Read(b, 0, b.Length);
            WavFormatHeader wfh = new WavFormatHeader(b);
            if(!wfh.Valid)
                throw new CannotReadException("No valid WAV Header found");

            info.Length = mh.Length;
            info.ChannelNumber = wfh.ChannelNumber ;
            info.SamplingRate = wfh.SamplingRate ;
            info.Bitrate = ComputeBitrate(info.Length, raf.Length) ;
            info.EncodingType = "Monkey Audio v" + (((double)version)/1000)+", compression level "+mh.CompressionLevel;
            info.ExtraEncodingInfos = "";

            return info;
        }
        public Id3v2Tag Read(Stream mp3Stream)
        {
            Id3v2Tag tag;

            byte[] b = new byte[3];

            mp3Stream.Read(b, 0, b.Length);
            mp3Stream.Seek(0, SeekOrigin.Begin);

            string ID3 = new string(System.Text.Encoding.ASCII.GetChars(b));

            if (ID3 != "ID3") {
                throw new CannotReadException("Not an ID3 tag");
            }
            //Begins tag parsing ---------------------------------------------
            mp3Stream.Seek(3, SeekOrigin.Begin);
            //----------------------------------------------------------------------------
            //Version du tag ID3v2.xx.xx
            string versionHigh=mp3Stream.ReadByte() +"";
            string versionID3 =versionHigh+ "." + mp3Stream.ReadByte();
            //------------------------------------------------------------------------- ---
            //D?tection de certains flags (A COMPLETER)
            this.ID3Flags = ProcessID3Flags( (byte) mp3Stream.ReadByte() );
            //----------------------------------------------------------------------------

            //			On extrait la taille du tag ID3
            int tagSize = ReadSyncsafeInteger(mp3Stream);
            //System.err.println("TagSize: "+tagSize);

            //			------------------NEWNEWNWENENEWNENWEWN-------------------------------
            //Fill a byte buffer, then process according to correct version
            b = new byte[tagSize+2];
            mp3Stream.Read(b, 0, b.Length);
            ByteBuffer bb = new ByteBuffer(b);

            if (ID3Flags[0]==true) {
                //We have unsynchronization, first re-synchronize
                bb = synchronizer.synchronize(bb);
            }

            if(versionHigh == "2") {
                tag = v23.Read(bb, ID3Flags, Id3v2Tag.ID3V22);
            }
            else if(versionHigh == "3") {
                tag = v23.Read(bb, ID3Flags, Id3v2Tag.ID3V23);
            }
            else if(versionHigh == "4") {
                throw new CannotReadException("ID3v2 tag version "+ versionID3 + " not supported !");
            }
            else {
                throw new CannotReadException("ID3v2 tag version "+ versionID3 + " not supported !");
            }

            return tag;
        }
Esempio n. 8
0
 private void ReadWriteStream(Stream readStream, Stream writeStream)
 {
     int count = 0x100;
     byte[] buffer = new byte[count];
     for (int i = readStream.Read(buffer, 0, count); i > 0; i = readStream.Read(buffer, 0, count))
     {
         writeStream.Write(buffer, 0, i);
     }
     readStream.Close();
     writeStream.Close();
 }
Esempio n. 9
0
        //接收线程
        public void receive()
        {
            filename = formm.filenamew[threadh];
            strUrl = formm.strurl;
            ns = null;
            nbytes = new byte[512];
            nreadsize = 0;

            Console.WriteLine("线程" + threadh.ToString() + "开始接收");
            if (!File.Exists(filename))
            {
                fs = new FileStream(filename, System.IO.FileMode.Create);
            }
            else
            {
                fs = File.OpenWrite(filename);
                DownLoadSize = fs.Length;
                formm.DownLoadtotal += DownLoadSize;
                formm.filestartw[threadh] += DownLoadSize;
                fs.Seek(DownLoadSize, SeekOrigin.Current);   //已经存在
            }
            if (!formm.threadw[threadh])
            {
                try
              {
                 request = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                //接收的起始位置及接收的长度
                 request.AddRange(formm.filestartw[threadh], formm.filestartw[threadh] + formm.filesizew[threadh]-DownLoadSize);
                 ns = request.GetResponse().GetResponseStream();//获得接收流
                 nreadsize = ns.Read(nbytes, 0, 512);

                 while (nreadsize > 0)
                 {
                    fs.Write(nbytes, 0, nreadsize);
                    nreadsize = ns.Read(nbytes, 0, 512);
                    formm.DownLoadtotal += 512;
                     Console.WriteLine("线程" + threadh.ToString() + "正在接收" + formm.DownLoadSpeed.ToString() + "k/s___已经下了" + formm.DownLoadtotal.ToString() + "还剩下" + formm.LeftDownLoadTime.ToString() + "s" + "百分比" + formm.DownLoadPercentage.ToString());
                 }
                 fs.Close();
                 ns.Close();
              }
               catch (Exception er)
              {
                Console.WriteLine("123");
                fs.Close();
              }
            }

               Console.WriteLine("进程" + threadh.ToString() + "接收完毕!");
            formm.threadw[threadh] = true;
        }
        public EncodingInfo Read( Stream raf )
        {
            EncodingInfo info = new EncodingInfo();

            //Begin info fetch-------------------------------------------
            if ( raf.Length==0 ) {
                //Empty File
                throw new CannotReadException("File is empty");
            }
            raf.Seek( 0 , SeekOrigin.Begin);

            //MP+ Header string
            byte[] b = new byte[3];
            raf.Read(b, 0, b.Length);
            string mpc = new string(System.Text.Encoding.ASCII.GetChars(b));
            if (mpc != "MP+" && mpc == "ID3") {
                //TODO Do we have to do this ??
                //we have an ID3v2 tag at the beginning
                //We quickly jump to MPC data
                raf.Seek(6, SeekOrigin.Begin);
                int tagSize = ReadSyncsafeInteger(raf);
                raf.Seek(tagSize+10, SeekOrigin.Begin);

                //retry to read MPC stream
                b = new byte[3];
                raf.Read(b, 0, b.Length);
                mpc = new string(System.Text.Encoding.ASCII.GetChars(b));
                if (mpc != "MP+") {
                    //We could definitely not go there
                    throw new CannotReadException("MP+ Header not found");
                }
            } else if (mpc != "MP+"){
                throw new CannotReadException("MP+ Header not found");
            }

            b = new byte[25];
            raf.Read(b, 0, b.Length);
            MpcHeader mpcH = new MpcHeader(b);
            //We only support v7 Stream format, so if it isn't v7, then returned values
            //will be bogus, and the file will be ignored

            double pcm = mpcH.SamplesNumber;
            info.Length = (int) ( pcm * 1152 / mpcH.SamplingRate );
            info.ChannelNumber = mpcH.ChannelNumber;
            info.SamplingRate = mpcH.SamplingRate;
            info.EncodingType = mpcH.EncodingType;
            info.ExtraEncodingInfos = mpcH.EncoderInfo;
            info.Bitrate = ComputeBitrate( info.Length, raf.Length );

            return info;
        }
        public override int ReadFrom(Stream channel)
        {
            this.ExpectIncomplete();
            var read = 0;

            // have we read the request size yet? 
            if (this.sizeBuffer.Remaining() > 0)
            {
                read += channel.Read(this.sizeBuffer.Array, 0, 4);
                this.sizeBuffer.Position = read;
            }

            // have we allocated the request buffer yet?
            if (this.contentBuffer == null && !this.sizeBuffer.HasRemaining())
            {
                this.sizeBuffer.Rewind();
                var size = this.sizeBuffer.GetInt();

                if (size <= 0)
                {
                    throw new InvalidRequestException(string.Format("{0} is not a valid request size", size));
                }

                if (size > this.MaxSize)
                {
                    throw new InvalidRequestException(
                        string.Format(
                            "Request of length {0} is not valid, it is larget than the maximum size of {1} bytes",
                            size,
                            this.MaxSize));
                }

                this.contentBuffer = this.ByteBufferAllocate(size);
            }

            // if we have a buffer read some stuff into it
            if (this.contentBuffer != null)
            {
                read = channel.Read(this.contentBuffer.Array, (int)(this.contentBuffer.ArrayOffset() + this.contentBuffer.Position), this.contentBuffer.Remaining());
                this.contentBuffer.Position += read;

                // did we get everything?
                if (!this.contentBuffer.HasRemaining())
                {
                    this.contentBuffer.Rewind();
                    this.complete = true;
                }
            }

            return read;
        }
        public EncodingInfo Read(Stream raf)
        {
            //Read the infos--------------------------------------------------------
            if (raf.Length == 0) {
                //Empty File
                throw new CannotReadException("Error: File empty");
            }
            raf.Seek(0, SeekOrigin.Begin);

            //FLAC Header string
            byte[] b = new byte[4];
            raf.Read(b, 0, b.Length);
            string flac = new string(System.Text.Encoding.ASCII.GetChars(b));
            if (flac != "fLaC") {
                throw new CannotReadException("fLaC Header not found");
            }

            MetadataBlockDataStreamInfo mbdsi = null;
            bool isLastBlock = false;
            while (!isLastBlock) {
                b = new byte[4];
                raf.Read(b, 0, b.Length);
                MetadataBlockHeader mbh = new MetadataBlockHeader(b);

                if (mbh.BlockType == (int) MetadataBlockHeader.BlockTypes.StreamInfo) {
                    b = new byte[mbh.DataLength];
                    raf.Read(b, 0, b.Length);

                    mbdsi = new MetadataBlockDataStreamInfo(b);
                    if (!mbdsi.Valid) {
                        throw new CannotReadException("FLAC StreamInfo not valid");
                    }
                    break;
                }
                raf.Seek(raf.Position + mbh.DataLength, SeekOrigin.Begin);

                isLastBlock = mbh.IsLastBlock;
                mbh = null; //Free memory
            }

            EncodingInfo info = new EncodingInfo();
            info.Length = mbdsi.Length;
            info.ChannelNumber = mbdsi.ChannelNumber;
            info.SamplingRate = mbdsi.SamplingRate;
            info.EncodingType = mbdsi.EncodingType;
            info.ExtraEncodingInfos = "";
            info.Bitrate = ComputeBitrate(mbdsi.Length, raf.Length);

            return info;
        }
        public Id3v1Tag Read( Stream mp3Stream )
        {
            Id3v1Tag tag = new Id3v1Tag();
            //Check wether the file contains an Id3v1 tag--------------------------------
            mp3Stream.Seek( -128 , SeekOrigin.End);

            byte[] b = new byte[3];
            mp3Stream.Read( b, 0, 3 );
            mp3Stream.Seek(0, SeekOrigin.Begin);
            string tagS = new string(System.Text.Encoding.ASCII.GetChars( b ));
            if(tagS != "TAG"){
                throw new CannotReadException("There is no Id3v1 Tag in this file");
            }

            mp3Stream.Seek( - 128 + 3, SeekOrigin.End );
            //Parse the tag -)------------------------------------------------
            string songName = Read(mp3Stream, 30);
            //------------------------------------------------
            string artist = Read(mp3Stream, 30);
            //------------------------------------------------
            string album = Read(mp3Stream, 30);
            //------------------------------------------------
            string year = Read(mp3Stream, 4);
            //------------------------------------------------
            string comment = Read(mp3Stream, 30);
            //------------------------------------------------
            string trackNumber = "";

            mp3Stream.Seek(- 2, SeekOrigin.Current);
            b = new byte[2];
            mp3Stream.Read(b, 0, 2);

            if ( b[0] == 0 ) {
                trackNumber = b[1].ToString ();
            }
            //------------------------------------------------
            byte genreByte = (byte) mp3Stream.ReadByte();
            mp3Stream.Seek(0, SeekOrigin.Begin);

            tag.SetTitle( songName );
            tag.SetArtist( artist );
            tag.SetAlbum( album );
            tag.SetYear( year );
            tag.SetComment( comment );
            tag.SetTrack( trackNumber );
            tag.SetGenre( tag.TranslateGenre(genreByte) );

            return tag;
        }
Esempio n. 14
0
	/**
	 * Receive a message of the given size from the inputstream.
	 * Makes sure the complete message is received, raises IOException otherwise.
	 */
	public static byte[] recv(Stream ins, int size) {
		byte [] bytes = new byte [size];
		int numRead = ins.Read(bytes, 0, size);
		if(numRead<=0) {
			throw new IOException("premature end of data");
		}
		while (numRead < size) {
			int len = ins.Read(bytes, numRead, size - numRead);
			if(len<=0) {
				throw new IOException("premature end of data");
			}
			numRead+=len;
		}
		return bytes;
	}
Esempio n. 15
0
        public Stream Echo(Stream data)
        {
            MemoryStream dataStorage = new MemoryStream();
            byte[] byteArray = new byte[8192];
            int bytesRead = data.Read(byteArray, 0, 8192);
            while (bytesRead > 0)
            {
                dataStorage.Write(byteArray, 0, bytesRead);
                bytesRead = data.Read(byteArray, 0, 8192);
            }
            data.Close();
            dataStorage.Seek(0, SeekOrigin.Begin);

            return dataStorage;
        }
Esempio n. 16
0
        public static dynamic[] Parse(Stream stream, Dictionary<int, string> fields)
        {
            var format = stream.Read<ulong>();
            stream.Position = 0;

            // DMsg format
            if (format == 0x00000067736D5F64)
            {
                return DMsgParser.Parse(stream, fields);
            }

            // Dialog format
            if ((format & 0x10000000) > 0 && format % 0x10000000 == (ulong) stream.Length - 4)
            {
                return DialogParser.Parse(stream, fields[0]);
            }

            // Auto-translate files (no specific format)
            if ((format & 0xFFFFFCFF) == 0x00010002)
            {
                return ATParser.Parse(stream, fields[0]);
            }

            throw new InvalidDataException("Unknown DAT format.");
        }
Esempio n. 17
0
        /// <summary>
        /// Gets the ID3v2 tag size from a specified stream.  Returns 0 if no tag exists.
        /// </summary>
        /// <param name="stream">The stream.</param>
        public static int GetTagSize(Stream stream)
        {
            try
            {
                if (stream.Length >= 16)
                {
                    stream.Position = 0;

                    byte[] identifier = stream.Read(3);

                    // 'ID3' identifier
                    if (!(identifier[0] == 0x49 && identifier[1] == 0x44 && identifier[2] == 0x33))
                    {
                        return 0;
                    }

                    IID3v2Header header = new ID3v2Header(stream, false);
                    int tagSize = header.TagSize;
                    if (tagSize != 0)
                        return tagSize + 10 + (header.IsFooterPresent ? 10 : 0);
                    else
                        return 0;
                }
                return 0;
            }
            finally
            {
                stream.Position = 0;
            }
        }
 public ManagedBitmap(Stream stream)
 {
     byte[] buffer = new byte[8];
     stream.Read(buffer, 0, buffer.Length);
     Width = buffer[4] << 8 | buffer[5];
     Height = buffer[6] << 8 | buffer[7];
     _colors = new Color[Width * Height];
     buffer = new byte[Width * Height * 4];
     stream.Read(buffer, 0, buffer.Length);
     int start = 0;
     for (int i = 0; i < _colors.Length; i++)
     {
         _colors[i] = Color.FromArgb(buffer[start], buffer[start + 1], buffer[start + 2], buffer[start + 3]);
         start += 4;
     }
 }
Esempio n. 19
0
        static MemoryStream StreamToMemory(Stream input)
        {
            byte[] buffer = new byte[1024];
            int count = 1024;
            MemoryStream output;

            // build a new stream
            if (input.CanSeek)
            {
                output = new MemoryStream((int)input.Length);
            }
            else
            {
                output = new MemoryStream();
            }

            // iterate stream and transfer to memory stream
            do
            {
                count = input.Read(buffer, 0, count);
                if (count == 0)
                    break; // TODO: might not be correct. Was : Exit Do
                output.Write(buffer, 0, count);
            } while (true);

            // rewind stream
            output.Position = 0;

            // pass back
            return output;
        }
        private static string AddToArchive(string entryName, Stream inputStream, ZipArchive zipArchive, string hashName)
        {
            var entry = zipArchive.CreateEntry(entryName);

            HashAlgorithm hashAlgorithm = null;
            BinaryWriter zipEntryWriter = null;
            try
            {
                hashAlgorithm = HashAlgorithm.Create(hashName);
                zipEntryWriter = new BinaryWriter(entry.Open());

                var readBuffer = new byte[StreamReadBufferSize];
                int bytesRead;
                while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                {
                    zipEntryWriter.Write(readBuffer, 0, bytesRead);
                    hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0);
                }
                hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0);

                var hashHexStringBuilder = new StringBuilder();
                foreach (byte hashByte in hashAlgorithm.Hash)
                {
                    hashHexStringBuilder.Append(hashByte.ToString("x2"));
                }

                return hashHexStringBuilder.ToString();
            }
            finally
            {
                hashAlgorithm.SafeDispose();
                zipEntryWriter.SafeDispose();
            }
        }
Esempio n. 21
0
 public GenericBinaryFile(Stream stream)
 {
     _path = string.Empty;
     _data = new byte[stream.Length];
     stream.Read(_data, 0, (int)stream.Length);
     stream.Dispose();
 }
        /// <summary>
        /// Reads the stream into a byte array.
        /// </summary>
        /// <param name="responseStream">The response stream.</param>
        /// <returns>A byte array.</returns>
        internal static byte[] ReadStream(Stream responseStream)
        {
            byte[] data = new byte[32768];

            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                bool exit = false;
                while (!exit)
                {
                    int read = responseStream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                    {
                        data = ms.ToArray();
                        exit = true;
                    }
                    else
                    {
                        ms.Write(buffer, 0, read);
                    }
                }
            }

            return data;
        }
Esempio n. 23
0
        /// <summary>
        /// Compute a hash from the content of a stream and restore the position.
        /// </summary>
        /// <remarks>
        /// Modified FNV Hash in C#
        /// http://stackoverflow.com/a/468084
        /// </remarks>
        internal static int ComputeHash(Stream stream)
        {
            System.Diagnostics.Debug.Assert(stream.CanSeek);

            unchecked
            {
                const int p = 16777619;
                var hash = (int)2166136261;

                var prevPosition = stream.Position;
                stream.Position = 0;

                var data = new byte[1024];
                int length;
                while((length = stream.Read(data, 0, data.Length)) != 0)
                {
                    for (var i = 0; i < length; i++)
                        hash = (hash ^ data[i]) * p;
                }

                // Restore stream position.
                stream.Position = prevPosition;

                hash += hash << 13;
                hash ^= hash >> 7;
                hash += hash << 3;
                hash ^= hash >> 17;
                hash += hash << 5;
                return hash;
            }
        }
Esempio n. 24
0
        private static Encoding GetFileEncoding(Stream fileStream)
        {
            var buffer = new byte[5];

            fileStream.Read(buffer, 0, 5);

            if (buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF)
                return new UTF32Encoding(true, true, true);
            if (buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0x00)
                return new UTF32Encoding(true, false, true);
            if (buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00)
                return new UTF32Encoding(false, true, true);
            if (buffer[1] == 0x00 && buffer[2] == 0x00 && buffer[3] == 0x00)
                return new UTF32Encoding(false, false, true);
            if (buffer[0] == 0xFE && buffer[1] == 0xFF)
                return new UnicodeEncoding(true, true, true);
            if (buffer[0] == 0x00)
                return new UnicodeEncoding(true, false, true);
            if (buffer[0] == 0xFF && buffer[1] == 0xFE)
                return new UnicodeEncoding(false, true, true);
            if (buffer[1] == 0x00)
                return new UnicodeEncoding(false, false, true);
            if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF)
                return new UTF8Encoding(true, true);
            return new UTF8Encoding(false, true);
        }
Esempio n. 25
0
        /// <summary>
        /// 压缩流数据
        /// </summary>
        /// <param name="aSourceStream"></param>
        /// <returns></returns>
        public static byte[] EnCompress(Stream aSourceStream)
        {
            MemoryStream vMemory = new MemoryStream();

            aSourceStream.Seek(0, SeekOrigin.Begin);
            vMemory.Seek(0, SeekOrigin.Begin);
            try
            {
                using (GZipStream vZipStream = new GZipStream(vMemory, CompressionMode.Compress))
                {
                    byte[] vFileByte = new byte[1024];
                    int vRedLen = 0;
                    do
                    {
                        vRedLen = aSourceStream.Read(vFileByte, 0, vFileByte.Length);
                        vZipStream.Write(vFileByte, 0, vRedLen);
                    }
                    while (vRedLen > 0);
                }
            }
            finally
            {
                vMemory.Dispose();
            }
            return vMemory.ToArray();
        }
        public static Stream Convert(Stream originalStream)
        {
            var copyData = new byte[originalStream.Length];
            originalStream.Read(copyData, 0, copyData.Length);
            var copyStream = new MemoryStream(copyData);

            var encoding = DetectEncoding(copyData);

            if (encoding == null)
                return copyStream;

            var utf8Suffix = new byte[] { 0xC2 };

            if (encoding == Encoding.UTF8 && IsDataSuffixed(copyData, utf8Suffix))
                copyStream.SetLength(copyStream.Length - utf8Suffix.Length);

            using (var copyReader = new StreamReader(copyStream, encoding))
            {
                var originalText = copyReader.ReadToEnd();
                var asciiData = Encoding.ASCII.GetBytes(originalText);
                var asciiText = Encoding.ASCII.GetString(asciiData);

                if (originalText == asciiText)
                    return new MemoryStream(asciiData);

                return CreateSuffixedStream(originalText, Encoding.UTF8, utf8Suffix);
            }
        }
Esempio n. 27
0
        public static FileType GetType(Stream sIn,out int offset)
        {
            int headSize = 76;
            if (sIn.Length < headSize)
                headSize = (int)sIn.Length;

            byte[] buffer = new byte[headSize];

            sIn.Read(buffer, 0, headSize);

            foreach (Detector detector in Detectors)
            {
                if (headSize <= detector.HeaderLength) continue;

                bool found = true;
                foreach (Data data in detector.Datas)
                    found &= ByteComp(buffer, data);

                if (found)
                {
                    offset = detector.FileOffset;
                    return detector.FType;
                }
            }

            offset = 0;
            return FileType.Nothing;
        }
Esempio n. 28
0
        /// <summary>
        /// Inflate the Feature option
        /// </summary>
        /// <param name="source">Stream to inflate the token from</param>
        /// <returns>TRUE if inflation is complete</returns>
        public override bool Inflate(Stream source)
        {
            // Reset inflation size
            InflationSize = 0;

            // Skip feature ID inflation because it was read by options collection

            // Read the length
            int length = (int)TDSUtilities.ReadUInt(source);

            // Update inflation size
            InflationSize += sizeof(int);

            // Allocate a container for the specified length
            Data = new byte[length];

            // Read the data
            source.Read(Data, 0, Data.Length);

            // Update inflation size
            InflationSize += (uint)length;

            // We've inflated the token option
            return true;
        }
Esempio n. 29
0
        public static byte[][] SearchHashes(Stream stream, IList<byte[]> hashes, int length = 32)
        {
            var result = new byte[hashes.Count][];

            Parallel.For(0, (int)(stream.Length / BLOCK_LENGTH), (int k) => {

                var hashProvider = new SHA1CryptoServiceProvider();
                var buffer = new byte[length];
                for (int i = 0; i < (BLOCK_LENGTH / ALIGN_LENGTH); i++)
                {
                    var position = k * BLOCK_LENGTH + i * ALIGN_LENGTH;
                    if (position >= stream.Length)
                        continue;

                    lock (stream)
                    {
                        stream.Position = position;
                        stream.Read(buffer, 0, length);
                    }

                    var hash = hashProvider.ComputeHash(buffer);
                    for (int j = 0; j < hashes.Count; j++)
                        if (hash.SequenceEqual(hashes[j]))
                            result[j] = (byte[])buffer.Clone();
                }

            });

            return result;
        }
 public static void Drain(Stream inStr)
 {
     var bs = new byte[BufferSize];
     while (inStr.Read(bs, 0, bs.Length) > 0)
     {
     }
 }
Esempio n. 31
0
    public static PlaneExtension Load(System.IO.Stream fs, Plane p)
    {
        var pe   = new PlaneExtension(p, null);
        var data = new byte[4];

        fs.Read(data, 0, data.Length);
        int structuresCount = System.BitConverter.ToInt32(data, 0);

        if (structuresCount > INNER_RESOLUTION * INNER_RESOLUTION || structuresCount < 0)
        {
            Debug.Log("surface block load error - incorrect structures count");
            GameMaster.LoadingFail();
            return(null);
        }
        else
        {
            if (structuresCount > 0)
            {
                Structure.LoadStructures(structuresCount, fs, p);
            }
        }
        return(pe);
    }
Esempio n. 32
0
        /// <summary>
        /// 接收从微信支付后台发送过来的数据未验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public static WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = HttpContext.Current.Request.InputStream;
            int count          = 0;

            byte[]        buffer  = new byte[1024];
            StringBuilder builder = new StringBuilder();

            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            //转换数据格式暂不验证签名
            WxPayData data = new WxPayData();

            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                HttpContext.Current.Response.Write(res.ToXml());
                HttpContext.Current.Response.End();
            }

            return(data);
        }
Esempio n. 33
0
        /// <summary>
        /// 接收从微信支付后台发送过来的数据并验证签名
        /// </summary>
        /// <returns>微信支付后台返回的数据</returns>
        public WxPayData GetNotifyData()
        {
            //接收从微信后台POST过来的数据
            System.IO.Stream s = Request.InputStream;
            int count          = 0;

            byte[]        buffer  = new byte[1024];
            StringBuilder builder = new StringBuilder();

            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();
            Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());
            //转换数据格式并验证签名
            WxPayData data = new WxPayData();

            try
            {
                data.FromXml(builder.ToString());
            }
            catch (WxPayException ex)
            {
                //若签名错误,则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", ex.Message);
                Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
                return(res);
            }

            return(data);
        }
        /// <summary>
        /// Gets the byte array from stream.
        /// </summary>
        /// <param name="media">The media.</param>
        /// <param name="rpu">The rpu.</param>
        /// <param name="caller">The caller.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev05, 2009-01-16</remarks>
        private static byte[] GetByteArrayFromStream(System.IO.Stream media, MLifter.DAL.Tools.StatusMessageReportProgress rpu, object caller)
        {
            int buffer_length = 10240;

            byte[] data = new byte[media.Length];
            StatusMessageEventArgs args = new StatusMessageEventArgs(StatusMessageType.CreateMediaProgress, (int)media.Length);

            media.Seek(0, SeekOrigin.Begin);

            int read = 0;
            int pos  = 0;

            do
            {
                read          = media.Read(data, pos, Math.Min(buffer_length, data.Length - pos));
                pos          += read;
                args.Progress = pos;
                if (rpu != null)
                {
                    rpu.Invoke(args, caller);
                }
            }while (read == buffer_length);
            return(data);
        }
Esempio n. 35
0
        /// <summary>
        /// 通过HTTP GET方式下载文件到指定的目录。
        /// </summary>
        /// <param name="url">需要下载的URL</param>
        /// <param name="destDir">需要下载到的目录</param>
        /// <returns>下载后的文件</returns>
        public static string Download(string url, string destDir)
        {
            string file = null;

            try
            {
                WebUtils        wu  = new WebUtils();
                HttpWebRequest  req = wu.GetWebRequest(url, "GET", null);
                HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
                if (CTYPE_OCTET.Equals(rsp.ContentType))
                {
                    file = Path.Combine(destDir, GetFileName(rsp.Headers["Content-Disposition"]));
                    using (System.IO.Stream rspStream = rsp.GetResponseStream())
                    {
                        int    len = 0;
                        byte[] buf = new byte[8192];
                        using (FileStream fileStream = new FileStream(file, FileMode.OpenOrCreate))
                        {
                            while ((len = rspStream.Read(buf, 0, buf.Length)) > 0)
                            {
                                fileStream.Write(buf, 0, len);
                            }
                        }
                    }
                }
                else
                {
                    throw new TopException(wu.GetResponseAsString(rsp, Encoding.UTF8));
                }
            }
            catch (WebException e)
            {
                throw new TopException("isv.file-already-download", e.Message);
            }
            return(file);
        }
Esempio n. 36
0
        static void ZapiszPlik(System.IO.Stream instream, string filePath)
        {
            const int bufferLength = 8192;
            int       bytecount    = 0;
            int       counter      = 0;

            byte[] buffer = new byte[bufferLength];
            Console.WriteLine("--->Zapisuje plik {0}", filePath);
            FileStream outstream = File.Open(filePath, FileMode.Create, FileAccess.Write);

            while ((counter = instream.Read(buffer, 0, bufferLength)) > 0)
            {
                outstream.Write(buffer, 0, counter);
                Console.Write(".{0}", counter);
                bytecount += counter;
            }
            Console.WriteLine();
            Console.WriteLine("Zapisano {0} bajtów", bytecount);

            outstream.Close();
            instream.Close();
            Console.WriteLine();
            Console.WriteLine("-->Plik {0} zapisany", filePath);
        }
Esempio n. 37
0
    public void Load(System.IO.Stream fs)
    {
        const int length = 48;
        var       data   = new byte[length];

        fs.Read(data, 0, length);
        int i = 0;

        float d(in int x)
        {
            return(System.BitConverter.ToSingle(data, x));
        }

        Vector3 v(in int x)
        {
            return(new Vector3(d(x), d(x + 4), d(x + 8)));
        }

        camBasisTransform.position = v(i); i += 12;
        camBasisTransform.rotation = Quaternion.Euler(v(i)); i += 12;
        camTransform.position      = v(i); i += 12;
        camTransform.rotation      = Quaternion.Euler(v(i));
        positionLoaded             = true;
    }
Esempio n. 38
0
        private void SaveFile(System.IO.Stream instream, string filePath)
        {
            const int bufferLength = 8192;
            int       bytecount    = 0;
            int       counter      = 0;

            byte[] buffer = new byte[bufferLength];
            Console.WriteLine("-->Saving file{0}", filePath);
            FileStream outstream = File.Open(filePath, FileMode.Create, FileAccess.Write);

            while ((counter = instream.Read(buffer, 0, bufferLength)) > 0)
            {
                outstream.Write(buffer, 0, counter);
                Console.Write(".{0}", counter);
                bytecount += counter;
            }
            Console.WriteLine();
            Console.WriteLine("Saved {0} bytes", bytecount);
            outstream.Close();
            instream.Close();
            Console.WriteLine();
            Console.WriteLine("-->File {0} saved", filePath);
            backgroundWorker.RunWorkerAsync();
        }
Esempio n. 39
0
        public static void CopyToStream(this System.IO.Stream sourceStream, System.IO.Stream targetStream, int bufferSize = 0)
        {
            if (null == sourceStream)
            {
                throw new ArgumentException("参数sourceStream不能为null");
            }
            if (null == targetStream)
            {
                throw new ArgumentException("参数targetStream不能为null");
            }
            bufferSize = bufferSize <= 0 ? 1024 * 1024 * 16 : bufferSize;
            byte[] buffer     = new byte[bufferSize];
            long   lPos       = 0;
            int    readLength = bufferSize;

            while (readLength > 0)
            {
                sourceStream.Seek(lPos, System.IO.SeekOrigin.Begin);
                readLength = sourceStream.Read(buffer, 0, buffer.Length);
                targetStream.Seek(lPos, System.IO.SeekOrigin.Begin);
                targetStream.Write(buffer, 0, readLength);
                lPos += readLength;
            }
        }
Esempio n. 40
0
        public static ZipEntry Read(System.IO.Stream s, bool TurnOnDebug)
        {
            ZipEntry entry = new ZipEntry();

            entry._Debug = TurnOnDebug;
            if (!ReadHeader(s, entry))
            {
                return(null);
            }

            entry.__filedata = new byte[entry.CompressedSize];
            int n = s.Read(entry._FileData, 0, entry._FileData.Length);

            if (n != entry._FileData.Length)
            {
                throw new Exception("badly formatted zip file.");
            }
            // finally, seek past the (already read) Data descriptor if necessary
            if ((entry._BitField & 0x0008) == 0x0008)
            {
                s.Seek(16, System.IO.SeekOrigin.Current);
            }
            return(entry);
        }
Esempio n. 41
0
    /// <summary>
    /// This method called when the page is loaded into the browser. This method requests input stream and parses it to get message counts.
    /// </summary>
    /// <param name="sender">object, which invoked this method</param>
    /// <param name="e">EventArgs, which specifies arguments specific to this method</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        System.IO.Stream stream = Request.InputStream;

        this.receivedDeliveryStatusFilePath = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
        if (string.IsNullOrEmpty(this.receivedDeliveryStatusFilePath))
        {
            this.receivedDeliveryStatusFilePath = "~\\DeliveryStatus.txt";
        }

        string count = ConfigurationManager.AppSettings["NumberOfDeliveryStatusToStore"];

        if (!string.IsNullOrEmpty(count))
        {
            this.numberOfDeliveryStatusToStore = Convert.ToInt32(count);
        }
        else
        {
            this.numberOfDeliveryStatusToStore = 5;
        }

        if (null != stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(bytes, 0, (int)stream.Length);
            string responseData = Encoding.ASCII.GetString(bytes);
            JavaScriptSerializer       serializeObject = new JavaScriptSerializer();
            DeliveryStatusNotification message         = (DeliveryStatusNotification)serializeObject.Deserialize(responseData, typeof(DeliveryStatusNotification));

            if (null != message)
            {
                this.SaveMessage(message);
            }
        }
    }
Esempio n. 42
0
        public static void CopyTo(this System.IO.Stream src, System.IO.Stream dest)
        {
            if (src == null)
            {
                throw new ArgumentNullException("src");
            }
            if (dest == null)
            {
                throw new ArgumentNullException("dest");
            }

            if (src.CanSeek)
            {
                src.Seek(0, SeekOrigin.Begin);
            }

            var buffer = new byte[4096];
            int cnt;

            while ((cnt = src.Read(buffer, 0, buffer.Length)) > 0)
            {
                dest.Write(buffer, 0, cnt);
            }
        }
        private void LoadFile()
        {
            OpenFileDialog FileDialog = new OpenFileDialog();

            FileDialog.Filter = "PNG files (*.png)|*.png|All files (*.*)|*.*";
            FileDialog.Title  = "Open Image";
            DialogResult result = FileDialog.ShowDialog(); // Show the dialog.

            if (result == DialogResult.OK)                 // Test result.
            {
                using (System.IO.Stream Stream = FileDialog.OpenFile())
                {
                    Data = new byte[Stream.Length];
                    Stream.Read(Data, 0, Data.Length);
                    Stream.Close();
                    Stream.Dispose();
                }
                FileDialog.Dispose();
            }
            else
            {
                return;
            }
        }
Esempio n. 44
0
        private void Load(
            )
        {
            /*
             * NOTE: Big-endian data expected.
             */
            System.IO.Stream      stream       = Stream;
            BigEndianBinaryReader streamReader = new BigEndianBinaryReader(stream);

            int index = 4;

            stream.Seek(index, SeekOrigin.Begin);
            byte[] markerBytes = new byte[2];
            while (true)
            {
                index += streamReader.ReadUInt16();
                stream.Seek(index, SeekOrigin.Begin);

                stream.Read(markerBytes, 0, 2);
                index += 2;

                // Frame header?
                if (markerBytes[0] == 0xFF &&
                    markerBytes[1] == 0xC0)
                {
                    stream.Seek(2, SeekOrigin.Current);
                    // Get the image bits per color component (sample precision)!
                    BitsPerComponent = stream.ReadByte();
                    // Get the image size!
                    Height = streamReader.ReadUInt16();
                    Width  = streamReader.ReadUInt16();

                    break;
                }
            }
        }
Esempio n. 45
0
 /// <summary>
 /// Convert Stream into byte[]
 /// </summary>
 /// <param name="obj">Object.</param>
 /// <returns>byte[].</returns>
 public byte[] toByteArray(object obj)
 {
     if (obj == null)
     {
         return(null);
     }
     try
     {
         System.IO.Stream body   = obj as System.IO.Stream;
         byte[]           buffer = new byte[16 * 1024];
         using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
             int read;
             while ((read = body.Read(buffer, 0, buffer.Length)) > 0)
             {
                 ms.Write(buffer, 0, read);
             }
             return(ms.ToArray());
         }
     }
     catch (Exception e)
     {
         throw new ApiException(500, e.Message);
     }
 }
        public System.IO.MemoryStream ReadLine()
        {
            // check and skip BOM in the beginning of file
            if (_logStream.Position == 0)
            {
                var bom       = Encoding.UTF8.GetPreamble();
                var bomBuffer = new byte[bom.Length];
                if (bomBuffer.Length != _logStream.Read(bomBuffer, 0, bomBuffer.Length) ||
                    !bomBuffer.SequenceEqual(bom))
                {
                    _logStream.Position = 0;
                }
            }

            var result = new MemoryStream(256);
            int thisByte;

            while (0 <= (thisByte = _logStream.ReadByte()))
            {
                if (result.Length == 0 &&
                    thisByte < 128 && // main ASCII set control or whitespace
                    (char.IsControl((char)thisByte) || char.IsWhiteSpace((char)thisByte))
                    )
                {
                    continue; // Ignore CR/LF and spaces in the beginning of the line
                }
                else if (thisByte == 10 || thisByte == 13)
                {
                    break; // EOL found
                }

                result.WriteByte((byte)thisByte);
            }

            return(result);
        }
Esempio n. 47
0
        public void ReadAndVerifyMac(System.IO.Stream s)
        {
            bool invalid = false;

            long PositionOfMac = s.Position;

            //Console.WriteLine("posn before reading MAC: {0} (0x{0:X2})", PositionOfMac);

            // read integrityCheckVector.
            // caller must ensure that the file pointer is in the right spot!
            _StoredMac = new byte[10];  // aka "authentication code"
            int n = s.Read(_StoredMac, 0, _StoredMac.Length);

            if (_StoredMac.Length != CalculatedMac.Length)
            {
                invalid = true;
            }

            if (!invalid)
            {
                for (int i = 0; i < _StoredMac.Length; i++)
                {
                    if (_StoredMac[i] != CalculatedMac[i])
                    {
                        invalid = true;
                    }
                }
            }

            if (invalid)
            {
                throw new Exception(String.Format("The MAC does not match '{0}' != '{1}'",
                                                  Util.FormatByteArray(_StoredMac),
                                                  Util.FormatByteArray(CalculatedMac)));
            }
        }
Esempio n. 48
0
        private static Assembly ResolveAssemblyFromResource(object sender, ResolveEventArgs e)
        {
            Assembly resourceAssembly;
            string   shortName = e.Name.Split(',')[0];

            if ((object)s_assemblyCache == null)
            {
                s_assemblyCache = new Dictionary <string, Assembly>();
            }

            resourceAssembly = s_assemblyCache[shortName];

            if ((object)resourceAssembly == null)
            {
                // Loops through all of the resources in the executing assembly.
                foreach (string name in Assembly.GetEntryAssembly().GetManifestResourceNames())
                {
                    // Sees if the embedded resource name matches the assembly it is trying to load.
                    if (string.Compare(FilePath.GetFileNameWithoutExtension(name), EntryAssembly.RootNamespace + "." + shortName, true) == 0)
                    {
                        // If so, loads embedded resource assembly into a binary buffer.
                        System.IO.Stream resourceStream = Assembly.GetEntryAssembly().GetManifestResourceStream(name);
                        byte[]           buffer         = new byte[resourceStream.Length];
                        resourceStream.Read(buffer, 0, (int)resourceStream.Length);
                        resourceStream.Close();

                        // Loads assembly from binary buffer.
                        resourceAssembly = Assembly.Load(buffer);
                        s_assemblyCache.Add(shortName, resourceAssembly);
                        break;
                    }
                }
            }

            return(resourceAssembly);
        }
Esempio n. 49
0
    /*******************************/
    /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary>
    /// <param name="sourceStream">The source Stream to read from.</param>
    /// <param name="target">Contains the array of characteres read from the source Stream.</param>
    /// <param name="start">The starting index of the target array.</param>
    /// <param name="count">The maximum number of characters to read from the source Stream.</param>
    /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns>
    public static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] target, int start, int count)
    {
        // Returns 0 bytes if not enough space in target
        if (target.Length == 0)
        {
            return(0);
        }

        byte[] receiver  = new byte[target.Length];
        int    bytesRead = sourceStream.Read(receiver, start, count);

        // Returns -1 if EOF
        if (bytesRead == 0)
        {
            return(-1);
        }

        for (int i = start; i < start + bytesRead; i++)
        {
            target[i] = (byte)receiver[i];
        }

        return(bytesRead);
    }
Esempio n. 50
0
        public override Image Load(System.IO.Stream s)
        {
            if (s.ReadByte() == 255)
            {
                byte[] buf = new byte[s.Length - 1];
                s.Read(buf, 0, buf.Length);
                s = new MemoryStream(Orvid.Compression.LZMA.Decompress(buf));
            }
            else
            {
                s.Position = 0;
            }
            byte[] tmp = new byte[8];
            s.Read(tmp, 0, 8); // skip the 8 empty bytes at the start of the file.
            tmp = new byte[4];
            s.Read(tmp, 0, 4);
            uint Height = ReadUInt32(tmp); // Read the Height.

            s.Read(tmp, 0, 4);
            uint  Width = ReadUInt32(tmp); // Read the Width.
            Image i = new Image((int)Width, (int)Height);
            byte  r, g, b, a;

            for (uint x = 0; x < Width; x++)
            {
                for (uint y = 0; y < Height; y++)
                {
                    r = (byte)s.ReadByte();
                    g = (byte)s.ReadByte();
                    b = (byte)s.ReadByte();
                    a = (byte)s.ReadByte();
                    i.SetPixel(x, y, new Pixel(r, g, b, a));
                }
            }
            return(i);
        }
Esempio n. 51
0
        public void DoDownload(string url, string fileName)
        {
            //WebRequestを作成
            System.Net.HttpWebRequest webreq =
                (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

            //サーバーからの応答を受信するためのWebResponseを取得
            System.Net.HttpWebResponse webres =
                (System.Net.HttpWebResponse)webreq.GetResponse();

            //応答データを受信するためのStreamを取得
            System.IO.Stream strm = webres.GetResponseStream();

            //ファイルに書き込むためのFileStreamを作成
            System.IO.FileStream fs = new System.IO.FileStream(
                fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

            //応答データをファイルに書き込む
            byte[] readData = new byte[1024];
            for (;;)
            {
                //データを読み込む
                int readSize = strm.Read(readData, 0, readData.Length);
                if (readSize == 0)
                {
                    //すべてのデータを読み込んだ時
                    break;
                }
                //読み込んだデータをファイルに書き込む
                fs.Write(readData, 0, readSize);
            }

            //閉じる
            fs.Close();
            strm.Close();
        }
Esempio n. 52
0
        /// <summary>
        /// Read from a stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="length">The number of bytes to read.</param>
        /// <param name="completed">The completed action.</param>
        /// <param name="error">The error action.</param>
        public static void Read(this System.IO.Stream stream, int length, Action <byte[]> completed, Action <Exception> error)
        {
            var buff = new byte[length];

            try
            {
                byte[] bytes = null;

                try
                {
                    // Read the data from the stream.
                    int len = stream.Read(buff, 0, length);
                    bytes = len < 1
                                  ? new byte[0]
                                  : len < length
                                    ? stream.ReadBytes(buff, len, length - len)
                                    : buff;
                }
                catch
                {
                    bytes = new byte[0];
                }

                if (completed != null)
                {
                    completed(bytes);
                }
            }
            catch (Exception ex)
            {
                if (error != null)
                {
                    error(ex);
                }
            }
        }
Esempio n. 53
0
        public static byte[] GetEmbeddedContent(string Resource)
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            string ns = "Wdk.IO";

            try
            {
                System.IO.Stream resStream = assembly.GetManifestResourceStream(ns + "." + Resource);
                if (resStream != null)
                {
                    byte[] myBuffer = new byte[resStream.Length];
                    resStream.Read(myBuffer, 0, (int)resStream.Length);
                    return(myBuffer);
                }
                else
                {
                    return(BytesOf("<!--- Resource {" + Resource.ToUpper() + "} not found under " + ns + " -->"));
                }
            }
            catch (Exception ex)
            {
                return(BytesOf(ex.ToString()));
            }
        }
Esempio n. 54
0
        public FilterStatus Filter(System.IO.Stream dataIn, out long dataInRead, System.IO.Stream dataOut, out long dataOutWritten)
        {
            if (dataIn == null)
            {
                dataInRead     = 0;
                dataOutWritten = 0;

                return(FilterStatus.Done);
            }

            dataInRead     = dataIn.Length;
            dataOutWritten = Math.Min(dataInRead, dataOut.Length);

            byte[] buffer    = new byte[dataOutWritten];
            int    bytesRead = dataIn.Read(buffer, 0, (int)dataOutWritten);

            dataOut.Write(buffer, 0, bytesRead);

            string s = System.Text.Encoding.UTF8.GetString(buffer);

            SaveContent(Entity, s);//写入文件
            //SaveImage(Entity, buffer);//写入文件
            return(FilterStatus.Done);
        }
Esempio n. 55
0
        public void DownloadFunc(String url, int fileCount, String file)
        {
            HttpWebRequest  httpRequest  = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();

            System.IO.Stream dataStream = httpResponse.GetResponseStream();
            byte[]           buffer     = new byte[8192];

            FileStream fs = new FileStream(folder + Convert.ToString(fileCount) + "." + file,
                                           FileMode.Create, FileAccess.Write);
            int size = 0;

            do
            {
                size = dataStream.Read(buffer, 0, buffer.Length);
                if (size > 0)
                {
                    fs.Write(buffer, 0, size);
                }
            } while (size > 0);
            fs.Close();

            httpResponse.Close();
        }
Esempio n. 56
0
        /// <summary>
        /// Загрузить объект
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        internal static byte[] GetResourceBytes(string name)
        {
            try
            {
                System.IO.Stream stream = null;

                stream = typeof(Tools).Assembly.GetManifestResourceStream(name);
                if (stream != null)
                {
                    long len = stream.Length;
                    if (len > 0)
                    {
                        byte[] buff = new byte[len];
                        stream.Read(buff, 0, (int)len);
                        return(buff);
                    }
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 57
0
        static void ZapiszPlik(System.IO.Stream instream, string filePath)
        {
            const int bufferLength = 8192; //długość bufora 8KB
            int       bytecount    = 0;    //licznik
            int       counter      = 0;    //licznik pomocniczy

            byte[] buffer = new byte[bufferLength];
            Console.WriteLine("--> Zapisuje plik {0}", filePath);
            FileStream outstream = File.Open(filePath, FileMode.Create, FileAccess.Write);

            //zapisywanie danych porcjami
            while ((counter = instream.Read(buffer, 0, bufferLength)) > 0)
            {
                outstream.Write(buffer, 0, counter);
                Console.Write(".{0}", counter); //wypisywanie info. po każdej części
                bytecount += counter;
            }
            Console.WriteLine();
            Console.WriteLine("Zapisano {0} bajtow", bytecount);
            outstream.Close();
            instream.Close();
            Console.WriteLine();
            Console.WriteLine("--> Plik {0} zapisany", filePath);
        }
Esempio n. 58
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // 请求方式大写
        string httpMethod = Request.HttpMethod.ToUpper();

        if (httpMethod == "GET")
        {
            string signature = Request["signature"] == null ? "" : Request["signature"];
            string timestamp = Request["timestamp"] == null ? "" : Request["timestamp"];
            string nonce     = Request["nonce"] == null ? "" : Request["nonce"];
            string echoStr   = Request["echoStr"] == null ? "" : Request["echoStr"];
            //log
            string log = "【" + httpMethod + "】" + DateTime.Now.ToString() + "|signature(" + signature + ")|timestamp(" + timestamp + ")|nonce(" + nonce + ")|echoStr(" + echoStr + ")";
            // WriteLog(log);
            WXPushLog("收到消息0GET", Request.Url.Query);
            Response.Write(echoStr);
            Response.End();
        }
        else if (httpMethod == "POST")
        {
            if (Request.InputStream != null)
            {
                System.IO.Stream sm = Request.InputStream;                        //获取post正文
                int    len          = (int)sm.Length;                             //post数据长度
                byte[] inputByts    = new byte[len];                              //字节数据,用于存储post数据
                sm.Read(inputByts, 0, len);                                       //将post数据写入byte数组中
                sm.Close();                                                       //关闭IO流
                string data = Encoding.GetEncoding("utf-8").GetString(inputByts); //转为unicode编码
                data = Server.UrlDecode(data);                                    //下面解释一下Server.UrlDecode和Server.UrlEncode的作用

                //WriteLog("【" + DateTime.Now + "收到消息】" + data);
                WXPushLog("收到消息0", data);
                SendMsgToUser(data);
            }
        }
    }
Esempio n. 59
0
        public override bool IsFrameEnd(System.IO.Stream stream)
        {
            try
            {
                if (stream.Length < 4)
                {
                    return(false);
                }

                bool isEnd = false;

                stream.Seek(-4, SeekOrigin.End);
                Byte[] tmpData = new byte[4];
                stream.Read(tmpData, 0, 4);
                if (tmpData.AreEquals(headerEndBytes))
                {
                    isEnd = true;
                }

                //for (int i = 0; i < tmpData.Length; i++)
                //{
                //    Debug.WriteLine(tmpData[i]);
                //}

                stream.Position = 0;
                StreamReader sr = new StreamReader(stream);
                // Debug.WriteLine(sr.ReadToEnd());

                stream.Seek(0, SeekOrigin.End);
                return(isEnd);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 60
0
    public void Load(System.IO.Stream fs)
    {
        var val = new byte[4];

        if (standartResources == null)
        {
            standartResources = new float[ResourceType.TYPES_COUNT];
        }
        totalVolume = 0f;
        float f;

        for (int i = 0; i < ResourceType.TYPES_COUNT; i++)
        {
            fs.Read(val, 0, 4);
            f = System.BitConverter.ToSingle(val, 0);
            if (f < 0)
            {
                Debug.Log("error in resource " + i.ToString() + ", count is " + f.ToString());
                f = 0;
            }
            standartResources[i] = f;
            totalVolume         += f;
        }
    }