Inheritance: IDisposable
Example #1
1
        public void Save()
        {
            Close();

            MemoryStream stream = new MemoryStream();
            BinaryWriter writer = new BinaryWriter(stream);

            Count = Images.Count;
            IndexList.Clear();

            int offSet = 8 + Count * 4;
            for (int i = 0; i < Count; i++)
            {
                IndexList.Add((int)stream.Length + offSet);
                Images[i].Save(writer);
                //Images[i] = null;
            }

            writer.Flush();
            byte[] fBytes = stream.ToArray();
            //  writer.Dispose();

            _stream = File.Create(FileName);
            writer = new BinaryWriter(_stream);
            writer.Write(LibVersion);
            writer.Write(Count);
            for (int i = 0; i < Count; i++)
                writer.Write(IndexList[i]);

            writer.Write(fBytes);
            writer.Flush();
            writer.Close();
            writer.Dispose();
            Close();
        }
	CustomAttributeWriter(ICustomAttributeWriterHelper helper) {
		this.helper = helper;
		this.recursionCounter = new RecursionCounter();
		this.outStream = new MemoryStream();
		this.writer = new BinaryWriter(outStream);
		this.genericArguments = null;
	}
Example #3
1
 static void WriteMagic(BinaryWriter writer)
 {
     foreach (char magic in spriteFontMagic)
     {
         writer.Write((byte)magic);
     }
 }
Example #4
1
 private void WriteStatic(BinaryWriter bw, HuedTile stat)
 {
     bw.Write((ushort)stat.ID);
     bw.Write((ushort)0);
     bw.Write((sbyte)stat.Z);
     bw.Write((ushort)stat.Hue);
 }
        public void Save(Stream output)
        {
            BinaryWriter writer = new BinaryWriter(output);

            writer.Write(this.version);
            writer.Write((int)0);
            writer.Write((int)0);

            // Double the string length since it's UTF16
            writer.Write((byte)(this.partName.Length * 2));
            MadScience.StreamHelpers.WriteStringUTF16(output, false, this.partName);

            writer.Write(this.blendType);
            this.blendTgi.Save(output);

            writer.Write((uint)this.geomBoneEntries.Count);
            for (int i = 0; i < this.geomBoneEntries.Count; i++)
            {
                this.geomBoneEntries[i].Save(output);
            }

            uint tgiOffset = (uint)output.Position - 8;
            // Why is this +12?  I dunno. :)
            this.keytable.size = 8;
            this.keytable.Save(output);
            output.Seek(4, SeekOrigin.Begin);
            writer.Write(tgiOffset);
            writer.Write(this.keytable.size);

            writer = null;
        }
Example #6
1
        /// <summary>
        /// 
        /// </summary>
        /// <param name="polygon"></param>
        /// <param name="writer"></param>
        public void Write(IPolygon polygon, BinaryWriter writer)
        {
            writer.Write((int) ShapeGeometryTypes.Polygon);

            // Write BoundingBox            
            WriteBoundingBox(polygon, writer);

            // Write NumParts and NumPoints            
            writer.Write((int) (polygon.NumInteriorRings + 1));
            writer.Write((int)  polygon.NumPoints);

            // Write IndexParts
            int count = 0;
            writer.Write((int) count);
            if (polygon.NumInteriorRings != 0)
            {
                // Write external shell index
                count += polygon.ExteriorRing.NumPoints;
                writer.Write((int) count);
                for (int i = 1; i < polygon.NumInteriorRings; i++)
                {
                    // Write internal holes index
                    count += polygon.GetInteriorRingN(i - 1).NumPoints;
                    writer.Write((int) count);
                }
            }

            // Write Coordinates
            for (int i = 0; i < polygon.NumPoints; i++)
                Write(polygon.Coordinates[i], writer);
        }
        /// <summary>
        /// Creates a <see cref="WaveFileWriter"/> that writes to a <see cref="Stream"/>.
        /// </summary>
        public WaveFileWriter(Stream outStream, WaveFormat format)
        {
            _ofstream = outStream;
            _writer = new BinaryWriter(outStream, UTF8);

            _writer.Write(UTF8.GetBytes("RIFF"));
            _writer.Write(0); // placeholder
            _writer.Write(UTF8.GetBytes("WAVEfmt "));
            _waveFormat = format;

            _writer.Write(18 + format.ExtraSize); // wave format Length
            format.Serialize(_writer);

            // CreateFactChunk
            if (format.Encoding != WaveFormatTag.Pcm)
            {
                _writer.Write(UTF8.GetBytes("fact"));
                _writer.Write(4);
                _factSampleCountPos = outStream.Position;
                _writer.Write(0); // number of samples
            }

            // WriteDataChunkHeader
            _writer.Write(UTF8.GetBytes("data"));
            _dataSizePos = outStream.Position;
            _writer.Write(0); // placeholder

            Length = 0;
        }
Example #8
1
        static void Main(string[] args)
        {
            FileStream filStream;
            BinaryWriter binWriter;

            Console.Write("Enter name of the file: ");
            string fileName = Console.ReadLine();
            if (File.Exists(fileName))
            {
                Console.WriteLine("File - {0} already exists!", fileName);
            }
            else
            {
                filStream = new FileStream(fileName, FileMode.CreateNew);
                binWriter = new BinaryWriter(filStream);
                decimal aValue = 2.16M;
                binWriter.Write("Sample Run");
                for (int i = 0; i < 11; i++)
                {

                    binWriter.Write(i);
                }
                binWriter.Write(aValue);

                binWriter.Close();
                filStream.Close();
                Console.WriteLine("File Created successfully");
            }

            Console.ReadKey();
        }
 public void TestIncompleteRewind()
 {
     MemoryStream ms = new MemoryStream();
     BinaryWriter bw = new BinaryWriter(ms);
     bw.Write(1);
     bw.Write(2);
     bw.Write(3);
     bw.Write(4);
     bw.Write(5);
     bw.Write(6);
     bw.Write(7);
     bw.Flush();
     ms.Position = 0;
     RewindableStream stream = new RewindableStream(ms);
     stream.StartRecording();
     BinaryReader br = new BinaryReader(stream);
     Assert.AreEqual(br.ReadInt32(), 1);
     Assert.AreEqual(br.ReadInt32(), 2);
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     stream.Rewind(true);
     Assert.AreEqual(br.ReadInt32(), 1);
     Assert.AreEqual(br.ReadInt32(), 2);
     stream.StartRecording();
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     Assert.AreEqual(br.ReadInt32(), 5);
     stream.Rewind(true);
     Assert.AreEqual(br.ReadInt32(), 3);
     Assert.AreEqual(br.ReadInt32(), 4);
     Assert.AreEqual(br.ReadInt32(), 5);
     Assert.AreEqual(br.ReadInt32(), 6);
     Assert.AreEqual(br.ReadInt32(), 7);
 }
Example #10
1
 private static string DeCrypting()
 {
     var res = string.Empty;
     var file = new FileStream(Controller.GetPath(), FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan);
     var reader = new BinaryReader(file);
     var writer = new BinaryWriter(new FileStream(Processor.GetNewName(Controller.GetPath()), FileMode.Create, FileAccess.Write,
         FileShare.None, 32, FileOptions.WriteThrough));
     try
     {
         var pos = 0;
         while (pos < file.Length)
         {
             var c = reader.ReadUInt16();
             //var pow = Processor.fast_exp(c, Controller.GetKc(), Controller.GetR());
             var pow = Processor.Pows(c, Controller.GetKc(), Controller.GetR());
             if (pos < 256) res += pow + " ";
             writer.Write((byte)(pow));
             pos += 2;
         }
     }
     finally
     {
         writer.Close();
         reader.Close();
     }
     return "Decoding Complete!\n" + res;
 }
        public DiscordAudioPacket(char seq, int timestamp, int ssrc, byte[] encodedaudio)
        {
            this.seq = seq;
            this.timestamp = timestamp;
            this.ssrc = ssrc;
            this.encodedAudio = encodedaudio;

            byte[] fullPacket = new byte[RTP_HEADER_BYTE_LENGTH + encodedAudio.Length];
            using (MemoryStream ms = new MemoryStream(fullPacket))
            {
                using (BinaryWriter writer = new BinaryWriter(ms))
                {
                    writer.BaseStream.Position = RTP_VERSION_PAD_EXTEND_INDEX;
                    writer.Write(RTP_VERSION_PAD_EXTEND);

                    writer.BaseStream.Position = RTP_PAYLOAD_INDEX;
                    writer.Write(RTP_PAYLOAD_TYPE);

                    writer.BaseStream.Position = SEQ_INDEX;
                    writer.Write(seq);

                    writer.BaseStream.Position = TIMESTAMP_INDEX;
                    writer.Write(timestamp);

                    writer.BaseStream.Position = SSRC_INDEX;
                    writer.Write(ssrc);

                    writer.BaseStream.Position = RTP_HEADER_BYTE_LENGTH;
                    writer.Write(fullPacket);
                }
            }
        }
 // DSFチャンクの数字はリトルエンディアンバイトオーダー
 private void BwWriteLE4(BinaryWriter bw, uint v)
 {
     bw.Write((byte)(v & 0xff));
     bw.Write((byte)((v >> 8) & 0xff));
     bw.Write((byte)((v >> 16) & 0xff));
     bw.Write((byte)((v >> 24) & 0xff));
 }
Example #13
1
 public void Write(BinaryWriter bw)
 {
     Shading.Write(bw);
     Main.Write(bw);
     _.Write(bw);
     __.Write(bw);
 }
Example #14
1
        public void writeBinary()
        {
            string nom = tbName.Text + ".bytes"; byte i;
            BinaryReader br = null;
            BinaryWriter bw = null;
            FileStream fs = null;
            //Ecriture d'octets dans le fichier
            bw = new BinaryWriter(File.Create(nom));

            i = Convert.ToByte(width.Text);
            bw.Write(i);

            i = Convert.ToByte(height.Text);
            bw.Write(i);

            i = Convert.ToByte(random.Checked);
            bw.Write(i);

            for (int j = 3; j < Convert.ToInt32(width.Text); j++)
            {
                bw.Write(Convert.ToSByte(0));
            }

            foreach (DataGridViewRow data in dataGridView1.Rows)
            {
                for(int j = 0; j < dataGridView1.Columns.Count;j++)
                {
                    i = Convert.ToByte(data.Cells[j].Value);

                    bw.Write(i);
                }
            }

            bw.Close();
        }
        public void MessageShouldBeSameAfterSerializationAndDeserialization()
        {
            var writer = new BinaryWriter(new MemoryStream());
            IMessageFactory msgFactory = new MessageFactory(new Message[]
                {
                    new ISomeServiceComplexRequest()
                });

            var fixture = new Fixture();
            fixture.Customize<ISomeServiceComplexRequest>(ob =>
                ob.With(x => x.datas,
                    fixture.CreateMany<SubData>().ToList()));
            fixture.Customize<ComplexData>(ob => ob
                .With(x => x.SomeArrString, fixture.CreateMany<string>().ToList())
                .With(x => x.SomeArrRec, fixture.CreateMany<SubData>().ToList()));

            var msg = fixture.CreateAnonymous<ISomeServiceComplexRequest>();

            //serialize and deserialize msg1
            msg.Serialize(writer);
            writer.Seek(0, SeekOrigin.Begin);
            var reader = new BinaryReader(writer.BaseStream);
            Message retMsg = msgFactory.Deserialize(reader);

            retMsg.Should().BeOfType<ISomeServiceComplexRequest>();
            msg.ShouldBeEqualTo((ISomeServiceComplexRequest)retMsg);
        }
Example #16
1
        // use static factory methods!
        private GnuPlot(Table table)
        {
            try {
                // TODO avoid necessary write access in app directory
                using (FileStream fs = new FileStream (BinaryFile, FileMode.Create, FileAccess.Write))
                    using (BinaryWriter bw = new BinaryWriter (fs)) {
                        Table3D t3D = table as Table3D;
                        if (t3D != null)
                            WriteGnuPlotBinary (bw, t3D);
                        else
                            WriteGnuPlotBinary (bw, (Table2D)table);
                    }
            } catch (Exception ex) {
                throw new GnuPlotException ("Could not write binary data file.\n" + ex.Message);
            }
            try {
                StartProcess (table);
            } catch (System.ComponentModel.Win32Exception ex) {
                // from MSDN
                // These are the Win32 error code for file not found or access denied.
                const int ERROR_FILE_NOT_FOUND = 2;
                const int ERROR_ACCESS_DENIED = 5;

                switch (ex.NativeErrorCode) {
                case ERROR_FILE_NOT_FOUND:
                    throw new GnuPlotProcessException ("Could not find gnuplot executable path:\n" + exePath + "\n\n" + ex.Message);
                case ERROR_ACCESS_DENIED:
                    throw new GnuPlotProcessException ("Access denied, no permission to start gnuplot process!\n" + ex.Message);
                default:
                    throw new GnuPlotProcessException ("Unknown error. Could not start gnuplot process.\n" + ex.Message);
                }
            }
        }
Example #17
1
 public void Patch(BinaryWriter file)
 {
     for (int i = 0; i < times; i++)
     {
         file.Write(repeat);
     }
 }
Example #18
1
 //解密
 public string Decrypt(string m,string key)
 {
     string msg = null;
     string[] array = m.Split('~');
     int length = array.Length;
     byte[] by = new byte[length];
     for (int i = 0; i < length;i++ )
     {
         int l = int.Parse(array[i]);
         byte[] k = System.BitConverter.GetBytes(l);
         by[i] = k[0];
     }
     try
     {
         FileStream aFile = new FileStream("2.txt", FileMode.Create);
         BinaryWriter sw = new BinaryWriter(aFile);
         sw.Write(by);
         sw.Close();
         aFile.Close();
     }
     catch (IOException e){}
     test.DES_Decrypt("2.txt", key, "3.txt");
     try
     {
         FileStream file = new FileStream("3.txt", FileMode.Open);
         StreamReader read = new StreamReader(file);
         msg=read.ReadToEnd();
         read.Close();
         file.Close();
     }
     catch (IOException) { }
     return msg;
 }
        public override byte[] GetEncoding()
        {
            try
            {
                MemoryStream outputStream = new MemoryStream();
                BinaryWriter binaryWriter = new BinaryWriter(new BufferedStream(outputStream));

                MessagesEncodingUtil.WriteMessageType(binaryWriter, this);

                if (PeerAddress.PrivateEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PrivateEndPoint.ToString());

                if (PeerAddress.PublicEndPoint == null)
                    MessagesEncodingUtil.WriteString(binaryWriter, "null");
                else
                    MessagesEncodingUtil.WriteString(binaryWriter, PeerAddress.PublicEndPoint.ToString());

                binaryWriter.Flush();

                byte[] buffer = outputStream.ToArray();

                if (buffer.Length <= EncodingConstants.MAX_MESSAGE_LENGTH)
                    return outputStream.ToArray();
                else
                    throw new BinaryEncodingException();
            }
            catch (Exception)
            {
                throw new BinaryEncodingException("Decode");
            }
        }
 public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter)
 {
     _client = client;
     _stream = stream;
     _binaryReader = binaryReader;
     _binaryWriter = binaryWriter;
 }
Example #21
1
        public void run(string text)
        {
          iSpeechSynthesis iSpeech=  new iSpeechSynthesis(_api, _production);

           iSpeech.setVoice("usenglishfemale");
           iSpeech.setOptionalCommands("format", "mp3");
            
           TTSResult result = iSpeech.speak(text);         
            
           byte [] audioData = new byte[result.getAudioFileLength()];

           int read = 0;
           int totalRead = 0;

           while (totalRead < audioData.Length)
           {
               read = result.getStream().Read(audioData, totalRead, audioData.Length - totalRead);
               totalRead += read;
           }


           FileStream fs = new FileStream("audio.mp3", FileMode.Create);
           BinaryWriter bw = new BinaryWriter(fs);

           bw.Write(audioData, 0, audioData.Length);           

        }
    // 
    // Write a object instance to data output stream
    //
    public override void TightMarshal2(OpenWireFormat wireFormat, Object o, BinaryWriter dataOut, BooleanStream bs) {
        base.TightMarshal2(wireFormat, o, dataOut, bs);

        RemoveInfo info = (RemoveInfo)o;
        TightMarshalCachedObject2(wireFormat, (DataStructure)info.ObjectId, dataOut, bs);

    }
Example #23
1
        /// <summary>
        /// Write the data of each frame in the file.
        /// </summary>
        /// <param name="controller">Controller that represent the device.</param>
        /// <param name="path">Path of the file where the data will be write.<br/>
        /// If one already exist it will be deleted and a new empty on is created.</param>
        public void RecordData(Controller controller, String path)
        {
            if (Directory.Exists(path) == true)
            {
                String destination = path + "leapMotion.data";
                try
                {
                    if (File.Exists(destination) == true)
                        File.Delete(destination);
                    file = File.Create(destination);
                }
                catch (ArgumentException e)
                {
                    throw e;
                }
            }
            else
                throw new System.ArgumentException("Destination path doesn't exist", "path");

            BinaryWriter writer = new BinaryWriter(file);
            for (int f = 9; f >= 0; f--)
            {
                Frame frameToSerialize = controller.Frame(f);
                byte[] serialized = frameToSerialize.Serialize;
                Int32 length = serialized.Length;
                writer.Write(length);
                writer.Write(serialized);
            }
        }
Example #24
0
 public void save(Stream file)
 {
     if (!file.CanWrite)
     {
         throw new NotSupportedException("Cannot write to stream");
     }
     using (var bw = new BinaryWriter(file))
     {
         long basePos = file.Position;
         bw.Write(0x01524142u);
         int fileC = fileList.Count;
         bw.Write(fileC);
         bw.Write(0u);
         bw.Write(0u);
         uint offset = 16*((uint) fileC + 1);
         for (int i = 0; i < fileC; i++)
         {
             file.Position = basePos + 16*(i + 1);
             BARFile bf = fileList[i];
             bw.Write(bf.type);
             bw.Write(bf._id);
             bw.Write(offset);
             bw.Write(bf.data.Length);
             uint szPad = (uint) Math.Ceiling((double) bf.data.Length/16)*16;
             file.Position = basePos + offset;
             bw.Write(bf.data);
             offset += szPad;
         }
     }
     //BinaryWriter should close file
 }
Example #25
0
	internal static byte[] WriteModWorld(BinaryWriter writer)
	{
		byte[] flags = new byte[numByteFlags];
		if (WriteChests(writer))
		{
			flags[0] |= 1;
		}
		if (TileIO.WriteTiles(writer))
		{
			flags[0] |= 2;
		}
		if (WriteNPCKillCounts(writer))
		{
			flags[0] |= 4;
		}
		if (TileIO.WriteContainers(writer))
		{
			flags[0] |= 8;
		}
		if (WriteAnglerQuest(writer))
		{
			flags[0] |= 16;
		}
		if (WriteCustomData(writer))
		{
			flags[0] |= 32;
		}
		return flags;
	}
        public static bool RequestImageComparisonStatus(string testName = null)
        {
            if (!Connect())
                throw new InvalidOperationException("Could not connect to image comparer server");

            try
            {
                if (testName == null && NUnit.Framework.TestContext.CurrentContext == null)
                {
                    testName = NUnit.Framework.TestContext.CurrentContext.Test.FullName;
                }

                var networkStream = ImageComparisonServer.GetStream();
                var binaryWriter = new BinaryWriter(networkStream);
                var binaryReader = new BinaryReader(networkStream);

                // Header
                binaryWriter.Write((int)ImageServerMessageType.RequestImageComparisonStatus);
                binaryWriter.Write(testName);

                return binaryReader.ReadBoolean();
            }
            catch (Exception)
            {
                throw;
            }
        }
        public ReplayRecorderConnection(IConnection inner, Func<string> chooseFilename)
        {
            this.chooseFilename = chooseFilename;
            this.inner = inner;

            writer = new BinaryWriter(preStartBuffer);
        }
        internal override void Write(BinaryWriter writer)
        {
            writer.Write(Version);
            writer.Write(VersionNeededToExtract);
            writer.Write((ushort) Flags);
            writer.Write((ushort) CompressionMethod);
            writer.Write(LastModifiedTime);
            writer.Write(LastModifiedDate);
            writer.Write(Crc);
            writer.Write(CompressedSize);
            writer.Write(UncompressedSize);

            byte[] nameBytes = EncodeString(Name);
            writer.Write((ushort) nameBytes.Length);
            //writer.Write((ushort)Extra.Length);
            writer.Write((ushort) 0);
            writer.Write((ushort) Comment.Length);

            writer.Write(DiskNumberStart);
            writer.Write(InternalFileAttributes);
            writer.Write(ExternalFileAttributes);
            writer.Write(RelativeOffsetOfEntryHeader);

            writer.Write(nameBytes);
            // writer.Write(Extra);
            writer.Write(Comment);
        }
        public int EncodeRun(string path)
        {
            // ID3タグを作ってサイズを調べる
            var id3Chunk = CreateID3v23Chunk();

            try {
                using (BinaryWriter bw = new BinaryWriter(
                        File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Write))) {
                    if (WriteDsdChunk(id3Chunk.Length, bw) < 0) {
                        return -1;
                    }
                    if (WriteFmtChunk(bw) < 0) {
                        return -1;
                    }
                    if (WriteDataChunk(bw) < 0) {
                        return -1;
                    }
                    if (WriteId3Chunk(id3Chunk, bw) < 0) {
                        return -1;
                    }
                }
            } catch (IOException ex) {
                Console.WriteLine(ex);
                return -1;
            }

            return 0;
        }
Example #30
0
 public MipsAssembler(Stream OutputStream)
 {
     this.Instructions = InstructionTable.ALL.ToDictionary((InstructionInfo) => InstructionInfo.Name);
     this.OutputStream = OutputStream;
     this.BinaryWriter = new BinaryWriter(this.OutputStream);
     this.BinaryReader = new BinaryReader(this.OutputStream);
 }