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 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); }
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(); }
static void WriteMagic(BinaryWriter writer) { foreach (char magic in spriteFontMagic) { writer.Write((byte)magic); } }
CustomAttributeWriter(ICustomAttributeWriterHelper helper) { this.helper = helper; this.recursionCounter = new RecursionCounter(); this.outStream = new MemoryStream(); this.writer = new BinaryWriter(outStream); this.genericArguments = null; }
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(); }
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); }
public void Write(BinaryWriter bw) { Shading.Write(bw); Main.Write(bw); _.Write(bw); __.Write(bw); }
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; }
// 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)); }
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); }
// // 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); }
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"); } }
/// <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; }
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); } } }
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); }
public ServerConnection(TcpClient client, SslStream stream, BinaryReader binaryReader, BinaryWriter binaryWriter) { _client = client; _stream = stream; _binaryReader = binaryReader; _binaryWriter = binaryWriter; }
/// <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); } }
public void Patch(BinaryWriter file) { for (int i = 0; i < times; i++) { file.Write(repeat); } }
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 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; }
/// <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); }
// 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); } } }
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 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 }
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); }
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; }
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 ReplayRecorderConnection(IConnection inner, Func<string> chooseFilename) { this.chooseFilename = chooseFilename; this.inner = inner; writer = new BinaryWriter(preStartBuffer); }
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 void Save(System.IO.Stream stream) { MemoryStream memoryStream = new MemoryStream(); var writer = new System.IO.BinaryWriter(memoryStream); writer.Write(dict.Count); foreach (KeyValuePair <string, LZ4Entry> pair in dict) { writer.Write(pair.Key); writer.Write(pair.Value.bytes.Length); writer.Write(pair.Value.bytes); } using (LZ4Stream lz4Stream = new LZ4Stream(stream, CompressionMode.Compress, LZ4StreamFlags.HighCompression)) { lz4Stream.Write(memoryStream.ToArray(), 0, (int)memoryStream.Length); } }
/** Serializes the graph settings to JSON and returns the data */ public byte[] Serialize(NavGraph graph) { #if !ASTAR_NO_JSON // Grab a cached string builder to avoid allocations var output = GetStringBuilder(); var writer = new JsonWriter(output, writerSettings); writer.Write(graph); return(encoding.GetBytes(output.ToString())); #else var mem = new System.IO.MemoryStream(); var writer = new System.IO.BinaryWriter(mem); var ctx = new GraphSerializationContext(writer); graph.SerializeSettings(ctx); return(mem.ToArray()); #endif }
internal override void Save() { if (!hasBattery) { return; } using (var file = new System.IO.BinaryWriter(new FileStream(saveFilePath, FileMode.Create))) { // We get the pointer byte[] memoryData = memory.MemoryData; // We need to save the current data into the rombanks Buffer.BlockCopy(memoryData, ramBank0Start, _state.RamBanksData, _state.CurrentRamBank * ramBankLength, ramBankLength); file.Write(_state.RamBanksData); } }
/// <summary> /// Serializes a the Attributes stored in this Instance to the BinaryStream /// </summary> /// <param name="writer">The Stream the Data should be stored to</param> /// <remarks> /// Be sure that the Position of the stream is Proper on /// return (i.e. must point to the first Byte after your actual File) /// </remarks> public void Serialize(System.IO.BinaryWriter writer) { writer.Write((int)verts.Count); if (verts.Count > 0) { writer.Write((int)items.Length); for (int i = 0; i < verts.Count; i++) { verts[i].Serialize(writer); } for (int i = 0; i < items.Length; i++) { this.WriteValue(writer, items[i]); } } }
public void Dispose() { Close(); if (_bDataFile == null) { return; } lock (_lockObject) { if (_bDataFile == null) { return; } _bDataFile.Dispose(); _bDataFile = null; } }
public int open_file(String File_name) { if (SFile == null) { SFile = new BinaryWriter(File.Open(File_name, FileMode.Create)); // SFile = new StreamWriter(File_name, false, Encoding.ASCII); Store_Data = true; return(1); } else { Store_Data = false; SFile.Close(); SFile = null; return(0); } }
public static byte[] CalculatePTK(byte[] pmk, byte[] stmac, byte[] bssid, byte[] snonce, byte[] anonce) { var pke = new byte[100]; var ptk = new byte[80]; using (var ms = new System.IO.MemoryStream(pke)) { using (var bw = new System.IO.BinaryWriter(ms)) { bw.Write(new byte[] { 0x50, 0x61, 0x69, 0x72, 0x77, 0x69, 0x73, 0x65, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x65, 0x78, 0x70, 0x61, 0x6e, 0x73, 0x69, 0x6f, 0x6e, 0 });/* Literally the string Pairwise key expansion, with a trailing 0*/ if (memcmp(stmac, bssid) < 0) { bw.Write(stmac); bw.Write(bssid); } else { bw.Write(bssid); bw.Write(stmac); } if (memcmp(snonce, anonce) < 0) { bw.Write(snonce); bw.Write(anonce); } else { bw.Write(anonce); bw.Write(snonce); } bw.Write((byte)0); // Will be swapped out on each round in the loop below } } for (byte i = 0; i < 4; i++) { pke[99] = i; var hmacsha1 = new HMACSHA1(pmk); hmacsha1.ComputeHash(pke); hmacsha1.Hash.CopyTo(ptk, i * 20); } return(ptk); }
public byte[] SaveStateBinary() { api.CMD_UpdateSerializeSize(); if (savebuff == null || savebuff.Length != api.comm->env.retro_serialize_size) { savebuff = new byte[api.comm->env.retro_serialize_size]; savebuff2 = new byte[savebuff.Length + 13]; } var ms = new System.IO.MemoryStream(savebuff2, true); var bw = new System.IO.BinaryWriter(ms); SaveStateBinary(bw); bw.Flush(); ms.Close(); return(savebuff2); }
private void lvl100_Click(object sender, EventArgs e) { FileStream update_save_open2 = null; BinaryWriter update_save_write2 = null; update_save_open2 = new System.IO.FileStream(savegame, System.IO.FileMode.OpenOrCreate); update_save_write2 = new System.IO.BinaryWriter(update_save_open2); #region data byte[] exp = BLKDTH_StringToByteArray(int.Parse(exp100box.Text).ToString("x6")); Array.Reverse(exp); update_save_open2.Position = Convert.ToInt64("778", 16); update_save_write2.Write(exp); byte[] expl = BLKDTH_StringToByteArray(int.Parse(expl8box.Text).ToString("X6")); Array.Reverse(expl); update_save_open2.Position = Convert.ToInt64("77C", 16); update_save_write2.Write(expl); byte[] lvl8 = BLKDTH_StringToByteArray(int.Parse(lvl100box.Text).ToString("X2")); Array.Reverse(lvl8); update_save_open2.Position = Convert.ToInt64("77B", 16); update_save_write2.Write(lvl8); byte[] rank = BLKDTH_StringToByteArray(int.Parse(rank100box.Text).ToString("X2")); Array.Reverse(rank); update_save_open2.Position = Convert.ToInt64("77F", 16); update_save_write2.Write(rank); byte[] exp1 = BLKDTH_StringToByteArray(int.Parse(exp100box1.Text).ToString("x6")); Array.Reverse(exp1); update_save_open2.Position = Convert.ToInt64("860", 16); update_save_write2.Write(exp1); byte[] exp1l = BLKDTH_StringToByteArray(int.Parse(expl8box.Text).ToString("X6")); Array.Reverse(exp1l); update_save_open2.Position = Convert.ToInt64("864", 16); update_save_write2.Write(exp1l); byte[] lvl81 = BLKDTH_StringToByteArray(int.Parse(lvl100box.Text).ToString("X2")); Array.Reverse(lvl81); update_save_open2.Position = Convert.ToInt64("863", 16); update_save_write2.Write(lvl81); byte[] rank1 = BLKDTH_StringToByteArray(int.Parse(rank100box.Text).ToString("X2")); Array.Reverse(rank1); update_save_open2.Position = Convert.ToInt64("867", 16); update_save_write2.Write(rank1); #endregion update_save_open2.Close(); }
public void SaveStateBinary(System.IO.BinaryWriter writer) { api.CMD_UpdateSerializeSize(); if (savebuff == null || savebuff.Length != api.comm->env.retro_serialize_size) { savebuff = new byte[api.comm->env.retro_serialize_size]; savebuff2 = new byte[savebuff.Length + 13]; } api.CMD_Serialize(savebuff); writer.Write(savebuff.Length); writer.Write(savebuff); // other variables writer.Write(Frame); writer.Write(LagCount); writer.Write(IsLagFrame); }
/// <summary> /// Trims mod stream of uninteresting record types /// </summary> /// <param name="streamCreator">A func to create an input stream</param> /// <param name="outputStream">Stream to write output to</param> /// <param name="interest">Specification of which record types to include</param> public static void Trim( Func <IMutagenReadStream> streamCreator, Stream outputStream, RecordInterest interest) { using var inputStream = streamCreator(); if (inputStream.Complete) { return; } using var writer = new System.IO.BinaryWriter(outputStream, Encoding.Default, leaveOpen: true); var fileLocs = RecordLocator.GetLocations( inputStream, interest: interest); // Import until first listed grup inputStream.Position = 0; if (!fileLocs.GrupLocations.TryGetInDirection( inputStream.Position, higher: true, result: out var nextRec)) { return; } var recordLocation = fileLocs.ListedRecords.Keys[nextRec.Key]; var noRecordLength = recordLocation - inputStream.Position - inputStream.MetaData.Constants.GroupConstants.HeaderLength; inputStream.WriteTo(outputStream, (int)noRecordLength); while (!inputStream.Complete) { var groupMeta = inputStream.GetGroup(readSafe: true); if (interest.IsInterested(groupMeta.ContainedRecordType)) { inputStream.WriteTo(outputStream, checked ((int)groupMeta.TotalLength)); } else { inputStream.Position += groupMeta.TotalLength; } } }
protected void ViewFile(string DBFile, string ApplicationNumber, string filename, string sPathToSaveFileTo, string TableName) { using (kvdConn) { kvdConn.Open(); using (SqlCommand cmd = new SqlCommand("select " + DBFile + " from " + TableName + " where [ApplicationNumber]='" + ApplicationNumber + "' ", kvdConn)) { using (SqlDataReader dr1 = cmd.ExecuteReader(System.Data.CommandBehavior.Default)) { if (dr1.Read()) { // read in using GetValue and cast to byte array byte[] fileData = ((byte[])dr1[DBFile]); // write bytes to disk as file using (System.IO.FileStream fs = new System.IO.FileStream(sPathToSaveFileTo, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { // use a binary writer to write the bytes to disk using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData); bw.Close(); } } } dr1.Close(); } } } //string strJavascript = "<script type='text/javascript'>window.open('Download.aspx?File="; //strJavascript += filename + "','_blank');</script>"; //Response.Write(strJavascript); //Response.Write("<script language='javascript'> window.open(Download.aspx?File='" + filename + "'); </script>"); string url = "Download.aspx?File=" + filename; string winUrl = "window.open('" + url + "', 'popup_window', 'width=1500,height=500,left=300,top=20,resizable=yes');"; ClientScript.RegisterStartupScript(this.GetType(), "script", winUrl, true); //Response.Redirect("Download.aspx?File=" + filename); //Response.Write("<script>"); //Response.Write("window.open('Download.aspx?File="+ filename+", '_newtab');"); //Response.Write("</script>"); }
//INICIO CODIGO AJENO //Fuente: https://sysdot.wordpress.com/2011/03/24/making-a-simple-audio-synthesizer-in-c/ public static void SaveIntoStream(double[] sampleData, long sampleCount, int samplesPerSecond) { // Export FileStream stream = File.Create("test.wav"); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); int RIFF = 0x46464952; int WAVE = 0x45564157; int formatChunkSize = 16; int headerSize = 8; int format = 0x20746D66; short formatType = 1; short tracks = 1; short bitsPerSample = 16; short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8)); int bytesPerSecond = samplesPerSecond * frameSize; int waveSize = 4; int data = 0x61746164; int samples = (int)sampleCount; int dataChunkSize = samples * frameSize; int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize; writer.Write(RIFF); writer.Write(fileSize); writer.Write(WAVE); writer.Write(format); writer.Write(formatChunkSize); writer.Write(formatType); writer.Write(tracks); writer.Write(samplesPerSecond); writer.Write(bytesPerSecond); writer.Write(frameSize); writer.Write(bitsPerSample); writer.Write(data); writer.Write(dataChunkSize); //FIN CODIGO AJENO //grabamos en el archivo cada valor de la onda foreach (double d in sampleData) { writer.Write((byte)d); } Console.WriteLine("TERMINADO"); Console.Read(); }
// Use this for initialization void Start() { MachineQrCommunication machineQrCommunication = new MachineQrCommunication(); string ServerResponse = machineQrCommunication.ReceiveDataFromServer(); //Receive the CAD file and save to Resources or local of the client machine MachineEntity machine = JsonUtility.FromJson <MachineEntity>(ServerResponse); instructionsEntity.operationId = machine.operationToDo; instructionsEntity.operationInstructionListId = machine.operationInstructionListId; instructionsEntity.operationInstructionList = machine.operationInstructionList; //Iterprete CAD Filename string CadFilenameAbsolute = machine.machineCADFile; string[] file = CadFilenameAbsolute.Split('/'); int counter = file.Length; string CadFilename = file[counter - 1]; //Exact Filename => example.obj //string CadFilename = "gokart_main_assy.obj"; //This filepath can be changed according to device string FilePath = "C:/ARClient/ARTeamcenterClient/Assets/Resources/" + CadFilename; byte[] FileBuffer = machineQrCommunication.ReceiveCADFileFromServer(); // create a file in local and write to file BinaryWriter bWrite = new System.IO.BinaryWriter(File.Open(FilePath, FileMode.Create)); bWrite.Write(FileBuffer); bWrite.Flush(); bWrite.Close(); //Load CAD model to the scene CADImage = OBJLoader.LoadOBJFile(FilePath); //I hope this will work //Display first step of the operation on the screen InstructionList = machine.operationInstructionList; size = InstructionList.Count; NextInformationButton.GetComponentInChildren <Text>().text = "Start"; InformationText.text = "You will see the instructions here!" + "If you feel you need more information, click the button below!"; //Highlight the part which will be changed }
// 注意:不能在初始化线程中调用 // static public void CheckInit() { if (logfile != null) { return; } try { // 创建文件 // string filePath = AppConst.LOCAL_LOG_PATH; if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } // 删除旧日志 // DirectoryInfo info = new DirectoryInfo(filePath); FileInfo[] files = info.GetFiles(); for (int i = 0; i < files.Length; ++i) { long deltaTicks = DateTime.Now.Ticks - files[i].LastWriteTime.Ticks; TimeSpan elapsedSpan = new TimeSpan(deltaTicks); if (elapsedSpan.Days >= 2) { files[i].Delete(); } } string fileName = filePath + "/Log_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".log"; #if ENCRYPT_LOG logfile = new System.IO.BinaryWriter(File.Open(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)); #else logfile = new System.IO.StreamWriter(fileName); #endif } catch (Exception e) { Debug.LogError("LOG日志文件初始化错误,请检查是否有文件读取权限:" + e); } // 监听系统LogError // Application.logMessageReceived += HandleSysLog; }
private Bitmap CreateBitmap(IntPtr hDC, Size bmpSize, byte[] data) { System.IO.MemoryStream mem = new System.IO.MemoryStream(); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(mem); //BITMAPINFO bmpInfo = new BITMAPINFO(); BITMAPINFOHEADER bmiHeader = new BITMAPINFOHEADER(); bmiHeader.biSize = 40; bmiHeader.biWidth = bmpSize.Width; bmiHeader.biHeight = bmpSize.Height; bmiHeader.biPlanes = 1; bmiHeader.biBitCount = 8; bmiHeader.biCompression = BI_RGB; bw.Write(bmiHeader.biSize); bw.Write(bmiHeader.biWidth); bw.Write(bmiHeader.biHeight); bw.Write(bmiHeader.biPlanes); bw.Write(bmiHeader.biBitCount); bw.Write(bmiHeader.biCompression); bw.Write(bmiHeader.biSizeImage); bw.Write(bmiHeader.biXPelsPerMeter); bw.Write(bmiHeader.biYPelsPerMeter); bw.Write(bmiHeader.biClrUsed); bw.Write(bmiHeader.biClrImportant); for (int i = 0; i < 256; i++) { bw.Write((byte)i); bw.Write((byte)i); bw.Write((byte)i); bw.Write((byte)0); } IntPtr hBitmap; if (data != null) { hBitmap = CreateDIBitmap(hDC, ref bmiHeader, CBM_INIT, data, mem.ToArray(), DIB_RGB_COLORS); } else { hBitmap = CreateDIBitmap(hDC, ref bmiHeader, 0, null, mem.ToArray(), DIB_RGB_COLORS); } return(Bitmap.FromHbitmap(hBitmap)); }
/// <summary> /// High quality /// </summary> /// <param name="img"></param> /// <returns></returns> public static Icon IconFromImage(Image img) { var ms = new System.IO.MemoryStream(); var bw = new System.IO.BinaryWriter(ms); // Header bw.Write((short)0); // 0 : reserved bw.Write((short)1); // 2 : 1=ico, 2=cur bw.Write((short)1); // 4 : number of images // Image directory var w = img.Width; if (w >= 256) { w = 0; } bw.Write((byte)w); // 0 : width of image var h = img.Height; if (h >= 256) { h = 0; } bw.Write((byte)h); // 1 : height of image bw.Write((byte)0); // 2 : number of colors in palette bw.Write((byte)0); // 3 : reserved bw.Write((short)0); // 4 : number of color planes bw.Write((short)0); // 6 : bits per pixel var sizeHere = ms.Position; bw.Write((int)0); // 8 : image size var start = (int)ms.Position + 4; bw.Write(start); // 12: offset of image data // Image data img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); var imageSize = (int)ms.Position - start; ms.Seek(sizeHere, System.IO.SeekOrigin.Begin); bw.Write(imageSize); ms.Seek(0, System.IO.SeekOrigin.Begin); // And load it return(new Icon(ms)); }
/// <summary> /// Saves texture into plugin dir with supplied name. /// Precondition: texture must be readable /// </summary> /// <param name="texture"></param> /// <param name="name"></param> public static bool SaveToDisk(this UnityEngine.Texture2D texture, string pathInGameData) { // texture format - needs to be ARGB32, RGBA32, RGB24 or Alpha8 var validFormats = new List <TextureFormat> { TextureFormat.Alpha8, TextureFormat.RGB24, TextureFormat.RGBA32, TextureFormat.ARGB32 }; if (!validFormats.Contains(texture.format)) { Log.Write("Texture to be saved has invalid format. Converting to a valid format."); return(CreateReadable(texture).SaveToDisk(pathInGameData)); } if (pathInGameData.StartsWith("/")) { pathInGameData = pathInGameData.Substring(1); } pathInGameData = "/GameData/" + pathInGameData; if (!pathInGameData.EndsWith(".png")) { pathInGameData += ".png"; } try { Log.Verbose("Saving a {0}x{1} texture as '{2}'", texture.width, texture.height, pathInGameData); System.IO.FileStream file = new System.IO.FileStream(KSPUtil.ApplicationRootPath + pathInGameData, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(file); writer.Write(texture.EncodeToPNG()); Log.Verbose("Texture saved as {0} successfully.", pathInGameData); return(true); } catch (Exception e) { Log.Error("Failed to save texture '{0}' due to {1}", pathInGameData, e); return(false); } }
public static bool Convert(System.IO.Stream input_stream, System.IO.Stream output_stream, int size, bool keep_aspect_ratio = false) { System.Drawing.Bitmap input_bit = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromStream(input_stream); if (input_bit != null) { int width, height; if (keep_aspect_ratio) { width = size; height = input_bit.Height / input_bit.Width * size; } else { width = height = size; } System.Drawing.Bitmap new_bit = new System.Drawing.Bitmap(input_bit, new System.Drawing.Size(width, height)); if (new_bit != null) { System.IO.MemoryStream mem_data = new System.IO.MemoryStream(); new_bit.Save(mem_data, System.Drawing.Imaging.ImageFormat.Png); System.IO.BinaryWriter icon_writer = new System.IO.BinaryWriter(output_stream); if (output_stream != null && icon_writer != null) { icon_writer.Write((byte)0); icon_writer.Write((byte)0); icon_writer.Write((short)1); icon_writer.Write((short)1); icon_writer.Write((byte)width); icon_writer.Write((byte)height); icon_writer.Write((byte)0); icon_writer.Write((byte)0); icon_writer.Write((short)0); icon_writer.Write((short)32); icon_writer.Write((int)mem_data.Length); icon_writer.Write((int)(6 + 16)); icon_writer.Write(mem_data.ToArray()); icon_writer.Flush(); return(true); } } return(false); } return(false); }
void StoreTreePage <T>(BTreePageBase <T> rootPage, io.BinaryWriter writer) where T : IComparable <T> { if (rootPage.IsLeaf) { //store id of left Int32 valueInt32 = Consts.BTreePageNodeItemsFlag; writer.Write(valueInt32); //offset ///////////////// TO BE USED AS AN ID ////////////////////////// var leaf = rootPage as BTreePageItems <T>; writer.Write(leaf.Offset); } else { //store page node var buffer = rootPage.ToBuffer(); writer.Write(buffer, 0, buffer.Length); //try to navigate left or right var node = rootPage as BTreePageNode <T>; int empty = 0; if (node.Left == null) { //signal, no left node writer.Write(empty); throw new ArgumentException($"Tree Node key:[{node.Root.Key}] has no left child"); } else { StoreTreePage <T>(node.Left, writer); } if (node.Right == null) { //signal, no right node writer.Write(empty); throw new ArgumentException($"Tree Node key:[{node.Root.Key}] has no right child"); } else { StoreTreePage <T>(node.Right, writer); } } }
private void WriteMapToOriginalFormat(System.IO.BinaryWriter worldFile) { int chunkwidth = 32; int chunkSize = chunkwidth * chunkwidth; byte[] chunk = new byte[chunkSize]; for (int chunkCount = 0; chunkCount < 64; chunkCount++) { // Copy the chunk over for (int i = 0; i < chunkSize; i++) { chunk[i] = _worldMapTiles[i % chunkwidth + chunkCount % 8 * chunkwidth, i / chunkwidth + chunkCount / 8 * chunkwidth]; } worldFile.Write(chunk); } }
/// <summary> /// Serializes a the Attributes stored in this Instance to the BinaryStream /// </summary> /// <param name="writer">The Stream the Data should be stored to</param> /// <remarks> /// Be sure that the Position of the stream is Proper on /// return (i.e. must point to the first Byte after your actual File) /// </remarks> public void Serialize(System.IO.BinaryWriter writer) { int count = transforms.Length; writer.Write((int)count); for (int i = 0; i < count; i++) { transforms[i].Order = VectorTransformation.TransformOrder.RotateTranslate; transforms[i].Serialize(writer); } writer.Write((int)names.Length); for (int i = 0; i < names.Length; i++) { names[i].Serialize(writer); } subset.Serialize(writer); }
public void ReadBytes_ReadsSimpleBytesAndGoesThroughMultipleBuffers() { var memoryStream = new MemoryStream(); var binaryWriter = new System.IO.BinaryWriter(memoryStream); binaryWriter.Write((Int16)16); binaryWriter.Write((uint)11); binaryWriter.Write(-12.0f); binaryWriter.Write(3.1112f); binaryWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); var reader = new BufferedStreamReader(memoryStream, 4); Assert.AreEqual(BitConverter.GetBytes((Int16)16), reader.ReadBytes(sizeof(Int16))); Assert.AreEqual(BitConverter.GetBytes((uint)11), reader.ReadBytes(sizeof(uint))); Assert.AreEqual(BitConverter.GetBytes(-12.0f), reader.ReadBytes(sizeof(float))); Assert.AreEqual(BitConverter.GetBytes(3.1112f), reader.ReadBytes(sizeof(float))); }
protected override void DoWrite(System.IO.BinaryWriter writer) { WriteString(writer, NodeName); if (KeyFrames == null) { writer.Write((Int32)0); } else { writer.Write((Int32)KeyFrames.Count); for (int i = 0; i < KeyFrames.Count; i++) { KeyFrames[i].Write(writer); } } }
private void InterpretADDA(System.IO.BinaryWriter outputFile, bool IsLabelScan) { EatWhiteSpaces(); if (sourceProgram[currentIndex] == '#') { currentIndex++; asLength += 2; if (IsLabelScan) { return; } ushort val = ReadByteValue(); if (!IsLabelScan) { outputFile.Write((byte)0x1F); outputFile.Write(val); } } }
/// <summary> /// Serializes a the Attributes stored in this Instance to the BinaryStream /// </summary> /// <param name="writer">The Stream the Data should be stored to</param> /// <remarks> /// Be sure that the Position of the stream is Proper on /// return (i.e. must point to the first Byte after your actual File) /// </remarks> public void Serialize(System.IO.BinaryWriter writer) { writer.Write((uint)unknown1); writer.Write(alternate); writer.Write(name); WriteBlock(writer, items1); if (parent.Version != 0x03) { writer.Write((uint)opacity); } if (parent.Version != 0x01) { WriteBlock(writer, items2); } }
public void convertByteArray2GiwerFormat(byte[] byIn, string filName) { if (byIn == null) { return; } using (System.IO.FileStream fs = new System.IO.FileStream(filName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { foreach (byte item in byIn) { bw.Write(item); } bw.Flush(); } } }
public void Serialize(System.IO.BinaryWriter writer) { if (parent.Format == 0x0000) { writer.Write(title); } else if (parent.Format == 0xFFFE) { writer.Write((byte)(lid - 1)); SerializeStringZero(writer, title); } else { writer.Write(lid); SerializeStringZero(writer, title); SerializeStringZero(writer, desc); } }
public void ToStream(System.IO.BinaryWriter bw) { bw.Write(this.elatt); bw.Write(this.scatt); bw.Write(ViewerUtils.ConvertStringToByteArray(this.Layer, 20)); bw.Write(this.laatt); bw.Write(this.xs); bw.Write(this.ys); bw.Write(this.xe); bw.Write(this.ye); bw.Write(this.xc); bw.Write(this.yc); bw.Write(this.Radius); bw.Write(this.Color); bw.Write(this.style); bw.Write(this.Width); bw.Write(ViewerUtils.ConvertStringToByteArray(this.Label, 20)); }
public static void BinarySave(this string text, io.BinaryWriter writer) { if (String.IsNullOrEmpty(text)) { text = String.Empty; } byte length = (byte)text.Length; writer.Write(length); var chars = text.ToCharArray(); //simple encode for (var i = 0; i < length; i++) { chars[i] = (char)((byte)(chars[i]) ^ MASK); } writer.Write(chars, 0, length); }