public void BinaryReader_DisposeTests() { // Disposing multiple times should not throw an exception using (Stream memStream = CreateStream()) using (BinaryReader binaryReader = new BinaryReader(memStream)) { binaryReader.Dispose(); binaryReader.Dispose(); binaryReader.Dispose(); } }
public static void EncodeFile(string sourceFilePath, string destinationFilePath) { FileStream fs_src = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read); BinaryReader br_src = new BinaryReader(fs_src); FileStream fs_dst = new FileStream(destinationFilePath, FileMode.Open, FileAccess.Write); BinaryWriter bw_dst = new BinaryWriter(fs_dst); string temp; ASCIIEncoding asci = new ASCIIEncoding(); while (fs_src.Length > fs_src.Position) { temp = string.Empty; temp += (char)br_src.ReadByte(); if (fs_src.Position + 1 < fs_src.Length) temp += (char)br_src.ReadByte(); if (fs_src.Position + 1 < fs_src.Length) temp += (char)br_src.ReadByte(); bw_dst.Write(Convert.ToBase64String(asci.GetBytes(temp))); } bw_dst.Close(); bw_dst.Dispose(); br_src.Close(); br_src.Dispose(); fs_src.Close(); fs_src.Dispose(); fs_dst.Close(); fs_dst.Dispose(); temp = null; }
private string fileString; //接收header的字符串 #endregion Fields #region Constructors //HeaderOnly的构造函数 public HeaderOnly(string name) : base(name) { fileString = ""; FileStream fs; //文件流 fs = new FileStream(name, FileMode.Open, FileAccess.Read); //从文件名读取一个文件流 string FileString = ""; fs.Seek(0, SeekOrigin.Begin); //设置文件开始读取的位置 BinaryReader reader = new BinaryReader(fs); //初始化二进制文件读写器,读取文件流 byte[] b = new byte[20]; //接收文件内容的byte数组 //异常处理 try { for (int i = 0; i < b.Length; i++) { b[i] = reader.ReadByte(); //将文件内容读入数组 } } catch (Exception) { throw; } fs.Close(); //关闭文件流,释放资源 reader.Dispose(); //释放二进制读取器的资源 for (int i = 0; i < b.Length; i++) { FileString += b[i].ToString("X2"); //将字节数组内容转为字符串(16进制) } fileString = FileString; Console.WriteLine(fileString); }
public bool CheckAddress(long offset, params byte[] bytes) { try { using (var br = new BinaryReader(File.Open(binary, FileMode.Open, FileAccess.Read))) { br.BaseStream.Seek(offset, SeekOrigin.Begin); for (int i = 0; i < bytes.Length; i++) { if (br.ReadByte() == bytes[i]) { Console.WriteLine("Binary already patched!"); br.Dispose(); return false; } } } return true; } catch (Exception ex) { Console.WriteLine("{0}", ex.Message); } if (File.Exists(binary)) File.Delete(binary); return false; }
/// <summary> /// Metoda za digitalno potpisivanje dokumenta /// </summary> /// <param name="file"></param> public void MakeDigitalSignature(string file) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader streamReader = new StreamReader("privatni_kljuc.txt"); string publicOnlyKeyXml = streamReader.ReadToEnd(); rsa.FromXmlString(publicOnlyKeyXml); streamReader.Close(); streamReader.Dispose(); FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read); BinaryReader binReader = new BinaryReader(dat); byte[] data = binReader.ReadBytes((int)dat.Length); byte[] sign = rsa.SignData(data, "SHA1"); binReader.Close(); binReader.Dispose(); dat.Close(); dat.Dispose(); string datName = file + ".dp"; TextWriter tw = new StreamWriter(datName); tw.WriteLine(Convert.ToBase64String(sign)); tw.Close(); tw.Dispose(); }
public byte[] ReadConvertedFile() { var count = 0; ReadFileAgain: try { /* var ext = Path.GetExtension(FullFilePath); if (ext == ".xls" || ext == ".xlsx") { return ReadXlsxFile(); } */ using (var fs = new FileStream(FileToSave, FileMode.Open, FileAccess.Read)) { var reader = new BinaryReader(fs); _convertedResult = reader.ReadBytes((int)fs.Length); reader.Close(); reader.Dispose(); fs.Close(); fs.Dispose(); } } catch (Exception) { System.Threading.Thread.Sleep(100); if (++count == 3) { throw; } goto ReadFileAgain; } return _convertedResult; }
public TIM(string path, byte arg0 = 0, bool paramsOnly = false) { this.arg0 = arg0 != 0; this.path = path; fs = new FileStream(path, FileMode.Open, FileAccess.Read); br = new BinaryReader(fs); texture = new Texture(); bpp = RecognizeBPP(); if (bpp == -1 && arg0==0) { Console.WriteLine("TIM: This is not TIM texture!"); return; } if (arg0 == 0 && !paramsOnly) { ReadParameters(bpp); bmp = DrawTexture(); } if (arg0 == 0 && paramsOnly) { ReadParameters(bpp); } br.Dispose(); fs.Dispose(); }
public void FixChannels(string BRSTMPath, int amount) { BinaryReader br = new BinaryReader(File.Open(BRSTMPath, FileMode.Open), Encoding.ASCII); const string Magic = "DATA"; int position = 0; for (int i = 0; i < br.BaseStream.Length; i += 4) { if (new String(br.ReadChars(4)) == Magic) //if we find the magic we can stop and we have our position { position = i + 4; br.Dispose(); br.Close(); break; } } BigEndianReader ber = new BigEndianReader(File.Open(BRSTMPath, FileMode.Open)); ber.BaseStream.Seek(position, SeekOrigin.Begin); uint value = ber.ReadUInt32() + 0x20; ber.Dispose(); ber.Close(); BigEndianWriter bw = new BigEndianWriter(File.Open(BRSTMPath, FileMode.Open)); bw.Seek(position, SeekOrigin.Begin); bw.Write(value); bw.Flush(); bw.Close(); BRSTMPath = '"' + BRSTMPath + '"'; //fix path DecodeBRSTM brstm = new DecodeBRSTM(); brstm.DecodeBRSTMDSP(BRSTMPath, amount); //pass value }
/// <summary> /// Creates a control command from raw data, starting at a certain offset in the raw data. /// </summary> /// <param name="rawCommand">The raw control command data.</param> /// <param name="startIndex">The start index to extract a control command at.</param> /// <returns>A control command that contains the information from the raw representation</returns> public static IControlCommand CreateFromRawCommand(byte[] rawCommand, int startIndex) { // inspect command length var length = rawCommand[startIndex]; // build the memory stream from the range var ms = new MemoryStream(rawCommand, startIndex, length); var br = new BinaryReader(ms); // consume the already known length byte length = br.ReadByte(); // extract the remaining meta data var dataType = (DataType)br.ReadInt32(); var action = (ControlCommandAction)br.ReadInt32(); ControlCommand command = null; if (dataType == DataType.Configuration) { command = new ConfigurationControlCommand(); } else { command = new ControlCommand(dataType, action); } command.Length = length; command.ReadData(br); br.Dispose(); return command; }
static void CalcCRC(string filename) { Debug.WriteLine(Path.GetFileName(filename)); var br = new BinaryReader(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)); int len = (int)br.BaseStream.Length; if (len <= 2) return; var data = br.ReadBytes(len ); var b1 = data[len-2]; var b2 = data[len-1]; //data[len - 2] = 0; //data[len - 1] = 0; br.Close(); br.Dispose(); int file_CRC_1 = (b1 << 8) + b2; //msb Debug.WriteLine("F: 0x{0:x4} ", file_CRC_1); int checksum_A = crcBig(data, data.Length - 2, 0x0000, 0x1021); Debug.WriteLine("crc 0x0000 0x{0:x4} ", checksum_A); }
public void Open(string fileName) { reader = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)); if (ReadReversed(reader) != 0x438CB47C) { Console.WriteLine("Invalid file"); reader.Close(); reader.Dispose(); } Unknown1 = ReadReversed(reader); NumFilesInTable = ReadReversed(reader); Checksum = ReadReversed(reader); ChecksumTableSize = ReadReversed(reader); Checksums = new int[ChecksumTableSize]; for (int i = 0; i < ChecksumTableSize; i++) { Checksums[i] = ReadReversed(reader); } Entrys = new BkArchiveEntry[NumFilesInTable]; for (int i = 0; i < NumFilesInTable; i++) { Entrys[i].ID = ReadReversed(reader); Entrys[i].Offset = ReadReversed(reader); Entrys[i].Size = ReadReversed(reader); } }
/// <summary> /// Metoda za verifikaciju ispravnosti digitalnog potpisa dokumenta /// </summary> /// <param name="file"></param> public void VerifyDigitalSignature(string file) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); StreamReader streamReader = new StreamReader("javni_kljuc.txt"); string publicKey = streamReader.ReadToEnd(); rsa.FromXmlString(publicKey); streamReader.Close(); streamReader.Dispose(); FileStream dat = new FileStream(file, FileMode.Open, FileAccess.Read); BinaryReader binReader = new BinaryReader(dat); byte[] data = binReader.ReadBytes((int)dat.Length); string nameP = file + ".dp"; TextReader streamreader = new StreamReader(nameP); string sign = streamreader.ReadLine(); streamreader.Close(); streamreader.Dispose(); if (rsa.VerifyData(data, "SHA1", Convert.FromBase64String(sign))) { MessageBox.Show("Datoteka je ispravno potpisana", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else MessageBox.Show("Datoteka nije ispravno potpisana", "My Application", MessageBoxButtons.OK, MessageBoxIcon.Warning); binReader.Close(); binReader.Dispose(); dat.Close(); dat.Dispose(); }
public void BinaryReader_DisposeTests_Negative() { using (Stream memStream = CreateStream()) { BinaryReader binaryReader = new BinaryReader(memStream); binaryReader.Dispose(); ValidateDisposedExceptions(binaryReader); } }
private void button2_Click(object sender, EventArgs e) { BinaryReader br = new BinaryReader(File.OpenRead(path)); br.BaseStream.Position = 0x1E;// set read position byte[] buffer = br.ReadBytes(2);//Read the wrong order 00 01 = 10 00 Array.Reverse(buffer); // reverse array to textBox1.Text = BitConverter.ToInt16(buffer, 0).ToString("x");//bitconvert to toint16, 32 four bytes use toInt32, ("x") = shows hex, .ToString() = decimal entire number. //bitconverter useful = turn a number into byte array. br.Dispose(); }
public void ExtractFile(string savePath, Stream file) { byte[] fileData = new byte[file.Length]; using (var br = new BinaryReader(file)) { fileData = br.ReadBytes((int)file.Length); br.Dispose(); br.Close(); } File.WriteAllBytes(savePath, fileData); file.Dispose(); file.Close(); }
private void button2_Click(object sender, EventArgs e) { BinaryReader br = new BinaryReader(File.OpenRead(path)); br.BaseStream.Position = 0x10;// in hex textBox1.Text = br.ReadChar().ToString();//read first character single //multi binary from above position foreach (char myChar in br.ReadChars(4)) textBox1.Text += myChar; br.Dispose(); textBox1.Text = br.ReadInt16().ToString("x");//reads right to left little indian byte order }
private void BtnFileOpenClick(object sender, EventArgs e) { var open = new OpenFileDialog(); open.Filter = "NPCGen (*.data)|*.data|All Files (*.*)|*.*"; if (open.ShowDialog() != DialogResult.OK || !File.Exists(open.FileName)) return; try { Cursor = Cursors.AppStarting; var fr = File.OpenRead(open.FileName); var br = new BinaryReader(fr); npcgen = new NPCGen(); npcgen.Version = br.ReadInt32(); npcgen.CreatureSetsCount = br.ReadInt32(); npcgen.ResourceSetsCount = br.ReadInt32(); switch (npcgen.Version) { case 10: npcgen.DynamicsCount = br.ReadInt32(); npcgen.TriggersCount = br.ReadInt32(); break; default: npcgen.DynamicsCount = 0; npcgen.TriggersCount = 0; break; } LoadCreatures(br); LoadResources(br); LoadDynamics(br); LoadTriggers(br); br.Dispose(); fr.Dispose(); Text = " sNPCedit (" + open.FileName + ")"; Cursor = Cursors.Default; } catch (Exception ex) { MessageBox.Show("Loading Error...\n" + ex.Message); Cursor = Cursors.Default; } }
private static void SetExpertMode(string source, string dest, bool expertMode) { BinaryReader reader = new BinaryReader(new FileStream(source, FileMode.Open)); int version = reader.ReadInt32(); if (version < 149) { MessageBox.Show("Error: Outdated terraria version"); return; } ulong magic = reader.ReadUInt64(); if ((magic & 72057594037927935uL) != 27981915666277746uL) { MessageBox.Show("Error: Invalid header"); return; } // Skip other file metadata... reader.ReadBytes(12); int positionCount = reader.ReadInt16(); int afterMetadataPos = reader.ReadInt32(); int afterHeaderPos = reader.ReadInt32(); // Skip positions... reader.ReadBytes((positionCount - 2) * 4); // Skip frame importance... reader.ReadBytes(reader.ReadInt16() / 8 + 1); if (reader.BaseStream.Position != afterMetadataPos) { MessageBox.Show("After Metadata Position Mismatch: expected " + afterMetadataPos + ", was " + reader.BaseStream.Position); return; } // Skip the first part of the header... reader.ReadString(); reader.ReadInt32(); reader.ReadInt32(); reader.ReadInt32(); reader.ReadInt32(); reader.ReadInt32(); reader.ReadInt32(); reader.ReadInt32(); // Get the offset... long expertModeFlagOffset = reader.BaseStream.Position; bool wasExpertMode = reader.ReadBoolean(); reader.Dispose(); // Notify the user if the world is changed... if (wasExpertMode == expertMode) { MessageBox.Show(expertMode ? "World was already Expert Mode." : "World was already not Expert Mode."); return; } BinaryWriter writer = new BinaryWriter(new FileStream(dest, FileMode.Open)); writer.BaseStream.Position = expertModeFlagOffset; writer.Write(expertMode); writer.Dispose(); MessageBox.Show(expertMode ? "World is now Expert Mode!" : "World is no longer Expert Mode!"); }
public Decode(byte[] buffer) { try { ms = new MemoryStream(buffer); br = new BinaryReader(ms); dataSize = br.ReadUInt16(); br.Close(); ms.Close(); br.Dispose(); ms.Dispose(); } catch (Exception ex) { Log.Exception(ex); } }
public Decode(byte[] buffer) { try { ms = new MemoryStream(buffer); br = new BinaryReader(ms); dataSize = br.ReadUInt16(); br.Close(); ms.Close(); br.Dispose(); ms.Dispose(); } catch (Exception ex) { Console.WriteLine("{0}", ex); } }
public Decode(byte[] buffer) { try { ms = new MemoryStream(buffer); br = new BinaryReader(ms); //dataSize = (ushort)br.ReadInt16(); br.Close(); ms.Close(); br.Dispose(); ms.Dispose(); } catch (Exception) { } }
/* * Function: ReadFile * Description:MATStrategy算法读取函数 * Parameters: * string sPath 文件路径 * StyleSet pStyle 绘制样式集 * Return Value:cNet */ cNet IfIOStrategy.ReadFile(string sPath) { int intType, intNum; cNet NewNet = null; Byte[,] bytMatrix; FileStream FS = null; BinaryReader Br = null; //文件系统流创建 FS = new FileStream(sPath, FileMode.Open); if (FS == null) { return null; } //二进制读写流创建 Br = new BinaryReader(FS, Encoding.ASCII); if (Br == null) { return null; } //读取文件头 Br.ReadBytes(intHeaderOffet); //循环读取数据元素 while(Br.BaseStream.Position < Br.BaseStream.Length) { //数据元素类型 4Byte intType = Br.ReadInt32(); //数据长度类型 4Byte intNum = Br.ReadInt32(); if(intType == intMatrixType) {//如果类型是矩阵才读入,否则跳到下一个数据元素块 if((Br.BaseStream.Length - Br.BaseStream.Position) >= intNum) { bytMatrix = DataInterpret(Br); if(bytMatrix == null) { break; } NewNet = BuileNetwork(bytMatrix); } break; } //多元素文件只取第一个矩阵 Br.ReadBytes(intNum); } Br.Close(); FS.Close(); Br.Dispose(); FS.Dispose(); return NewNet; }
/// <summary> /// Opens the specified archive for reading. /// </summary> /// <param name="filename">Path of the file to read.</param> /// <exception cref="InvalidDataException">The file format is not /// supported.</exception> /// <exception cref="IOException">An IO error occurred.</exception> public PkgArchive(string filename) { this.filename = filename; this.reader = new BinaryReader( new FileStream(filename, FileMode.Open, FileAccess.Read)); try { ReadHeaderAndIndexSection(); } catch (Exception) { reader.Dispose(); throw; } }
public SkeletonReplay(Stream stream) { BinaryReader reader = new BinaryReader(stream); int frameNumber = 0; while (reader.BaseStream.Position != reader.BaseStream.Length) { ReplaySkeletonFrame frame = new ReplaySkeletonFrame(reader, frameNumber++); frames.Add(frame); } reader.Dispose(); stream.Dispose(); }
public void BinaryWriter_WriteCharTest() { Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); BinaryReader dr2 = new BinaryReader(mstr); char[] chArr = new char[0]; int ii = 0; // [] Write a series of characters to a MemoryStream and read them back chArr = new char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' }; for (ii = 0; ii < chArr.Length; ii++) dw2.Write(chArr[ii]); dw2.Flush(); mstr.Position = 0; for (ii = 0; ii < chArr.Length; ii++) { char c = dr2.ReadChar(); Assert.Equal(chArr[ii], c); } Assert.Throws<EndOfStreamException>(() => dr2.ReadChar()); dw2.Dispose(); dr2.Dispose(); mstr.Dispose(); //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. //They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF char ch; Stream mem = CreateStream(); BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); //between 1 <= x < 255 int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 }; for (int i = 0; i < randomNumbers.Length; i++) { ch = (char)randomNumbers[i]; writer.Write(ch); } mem.Position = 0; writer.Dispose(); mem.Dispose(); }
public void Read() { if(path == null) return; FileStream fs = new FileStream(path, FileMode.Open,FileAccess.Read); BinaryReader br = new BinaryReader(fs); uint n = 0; uint len = (uint)fs.Length; nClips = 0; while (n < len) { fs.Seek(n, SeekOrigin.Begin); uint header = br.ReadUInt32() & 0xFFFFFF; if (header != 0x503846) return; fs.Seek(2, SeekOrigin.Current); _mClips[nClips].Frames = br.ReadUInt16(); n += 8; fs.Seek(n+8, SeekOrigin.Begin); fs.Seek(_mClips[nClips].Frames*0x2C+(0x2C-8), SeekOrigin.Current); header = br.ReadUInt32() & 0xFFFFFF; if (header != 0x4B4942) return; _mClips[nClips].Resolutions[0].Offset = (uint)fs.Position-4; _mClips[nClips].Resolutions[0].Size = br.ReadUInt32(); _mClips[nClips].Frames = br.ReadUInt32(); _mClips[nClips].Resolutions[0].Size += 8; n = _mClips[nClips].Resolutions[0].Size + _mClips[nClips].Resolutions[0].Offset; fs.Seek(n, SeekOrigin.Begin); header = br.ReadUInt32() & 0xFFFFFF; if(header != 0x4B4942) return; _mClips[nClips].Resolutions[1].Offset = _mClips[nClips].Resolutions[0].Offset + _mClips[nClips].Resolutions[0].Size; _mClips[nClips].Resolutions[1].Size = br.ReadUInt32(); _mClips[nClips].Resolutions[1].Size += 8; n += _mClips[nClips].Resolutions[1].Size; nClips++; } bSuccess = true; br.Dispose(); fs.Dispose(); }
/// <summary> /// 將檔案轉換為 Byte /// </summary> /// <param name="path"></param> /// <returns></returns> public static byte[] ReadFile(string path) { byte[] data = null; FileInfo fInfo = new FileInfo(path); long length = fInfo.Length; FileStream fStream = new FileStream(path, FileMode.Open, FileAccess.Read); using (BinaryReader br = new BinaryReader(fStream)) { data = br.ReadBytes((int)length); br.Close(); br.Dispose(); } return data; }
/// <summary> /// Reading by worker settings Chief passed. /// </summary> /// <param name="workerSettingsPipeHandle">Settings pipe handler.</param> /// <param name="workerLogPipe">Log redirector setting.</param> /// <param name="workerSettings">Worker settings.</param> /// <param name="chiefProcess">Chief process.</param> public static void ReadSettings( string workerSettingsPipeHandle, out ILog workerLogPipe, out ServerSettingsBase workerSettings, out Process chiefProcess) { using (var workerControlPipe = new AnonymousPipeClientStream(PipeDirection.In, workerSettingsPipeHandle)) { var binaryReader = new BinaryReader(workerControlPipe); workerLogPipe = new AnonymousPipeClientStreamLog(binaryReader.ReadString()); chiefProcess = Process.GetProcessById(binaryReader.ReadInt32()); workerLogPipe.Open(); workerSettings = (ServerSettingsBase)new BinaryFormatter().Deserialize(workerControlPipe); binaryReader.Dispose(); // because it closes underlying stream. } }
public void Play(Stream stream) { _lastFrameTime = 0; var reader = new BinaryReader(stream); _cancellationTokenSource = new CancellationTokenSource(); var cancelToken = _cancellationTokenSource.Token; Task.Factory.StartNew(() => { while (reader.BaseStream.Position != reader.BaseStream.Length) { var frameType = (TFrameType)reader.ReadInt32(); switch (frameType) { case TFrameType.TColorFrame: var colorFrame = new TColorFrame(); colorFrame.Read(reader); SpeedControll(colorFrame.Timestamp); ColorFrameReady(this, colorFrame); break; case TFrameType.TDepthFrame: var depthFrame = new TDepthFrame(); depthFrame.Read(reader); SpeedControll(depthFrame.Timestamp); DepthFrameReady(this, depthFrame); break; case TFrameType.TSkeletonFrame: var skeletonFrame = new TSkeletonFrame(); skeletonFrame.Read(reader); SpeedControll(skeletonFrame.Timestamp); SkeletonFrameReady(this, skeletonFrame); break; } } reader.Close(); reader.Dispose(); if (ReplayEnded != null) ReplayEnded(this,"Ended"); }, cancelToken); }
public Decode(byte[] buffer) { try { byte[] _tempbuff = new byte[buffer.Length]; EncDcd endc = new EncDcd(); _tempbuff = endc.Crypt(buffer); ms = new MemoryStream(_tempbuff); br = new BinaryReader(ms); dataSize = (ushort)br.ReadInt16(); tempbuff = new byte[dataSize]; Buffer.BlockCopy(_tempbuff, 0, tempbuff, 0, dataSize); br.Close(); ms.Close(); br.Dispose(); ms.Dispose(); _tempbuff = null; endc = null; } catch (Exception) { } }