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 Encoding GetFileEncodeType(string filename) { FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); BinaryReader br = new System.IO.BinaryReader(fs); Byte[] buffer = br.ReadBytes(2); if (buffer[0] >= 0xEF) { if (buffer[0] == 0xEF && buffer[1] == 0xBB) { br.Dispose(); br.Close(); fs.Dispose(); fs.Close(); return(System.Text.Encoding.UTF8); } else if (buffer[0] == 0xFE && buffer[1] == 0xFF) { br.Dispose(); br.Close(); fs.Dispose(); fs.Close(); return(System.Text.Encoding.BigEndianUnicode); } else if (buffer[0] == 0xFF && buffer[1] == 0xFE) { br.Dispose(); br.Close(); fs.Dispose(); fs.Close(); return(System.Text.Encoding.Unicode); } else { br.Dispose(); br.Close(); fs.Dispose(); fs.Close(); return(System.Text.Encoding.Default); } } else { br.Dispose(); br.Close(); fs.Dispose(); fs.Close(); return(System.Text.Encoding.Default); } }
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 }
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; }
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); }
/// <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 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> /// 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; }
/// <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(); }
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 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 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(); }
/// <summary> /// Re load the schema structure of the database from disk /// </summary> /// <returns>true if loaded successfully</returns> public bool Load() { try { var reader = new io.BinaryReader(io.File.OpenRead(SchemaFilePath)); Schema = DbSchemaConfig.Load(reader); reader.Dispose(); //link foreach (var table in Tables) { table.Database = this; foreach (var column in table.Columns) { //update if (!column.Indexed) { column.NodePages = 0; column.ItemPages = 0; } column.Table = table; } } ; SaveKeyIndexedKeyOffsets(); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
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; }
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; }
public override void Dispose() { if (reader != null) { reader.Dispose(); reader = null; } }
/// <summary> /// Generate a list of DatItem objects from the header values in an archive /// </summary> /// <param name="omitFromScan">Hash representing the hashes that should be skipped</param> /// <param name="date">True if entry dates should be included, false otherwise (default)</param> /// <returns>List of DatItem objects representing the found data</returns> /// <remarks>TODO: All instances of Hash.DeepHashes should be made into 0x0 eventually</remarks> public override List <BaseFile> GetChildren(Hash omitFromScan = Hash.DeepHashes, bool date = false) { if (_children == null || _children.Count == 0) { _children = new List <BaseFile>(); string gamename = Path.GetFileNameWithoutExtension(_filename); BaseFile possibleTgz = GetTorrentGZFileInfo(); // If it was, then add it to the outputs and continue if (possibleTgz != null && possibleTgz.Filename != null) { _children.Add(possibleTgz); } else { try { // If secure hashes are disabled, do a quickscan if (omitFromScan == Hash.SecureHashes) { BaseFile tempRom = new BaseFile() { Filename = gamename, }; BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename)); br.BaseStream.Seek(-8, SeekOrigin.End); byte[] headercrc = br.ReadBytesReverse(4); tempRom.CRC = headercrc; tempRom.Size = br.ReadInt32Reverse(); br.Dispose(); _children.Add(tempRom); } // Otherwise, use the stream directly else { GZipStream gzstream = new GZipStream(Utilities.TryOpenRead(_filename), Ionic.Zlib.CompressionMode.Decompress); BaseFile gzipEntryRom = Utilities.GetStreamInfo(gzstream, gzstream.Length, omitFromScan: omitFromScan); gzipEntryRom.Filename = gzstream.FileName; gzipEntryRom.Parent = gamename; gzipEntryRom.Date = (date && gzstream.LastModified != null ? gzstream.LastModified?.ToString("yyyy/MM/dd hh:mm:ss") : null); _children.Add(gzipEntryRom); gzstream.Dispose(); } } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return(null); } } } return(_children); }
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(); }
/// <summary> /// Image: prefix[6] + change[1] + size[1] + message_bytes /// </summary> public void CaptureTextFromPosition(out int change, out string message, Screen screen) { change = 0; message = null; if (screen == null) { return; } var x = SettingsManager.Options.DisplayMonitorPositionX; var y = SettingsManager.Options.DisplayMonitorPositionY; var sw = screen.Bounds.Width; var sh = screen.Bounds.Height; // Make sure take pixel pairs till the end of the line. var length = sw - x; length = length - (length % 2); // Take screenshot of the line. Basic.CaptureImage(ref lineBitmap, screen.Bounds.X + x, screen.Bounds.Y + y, length, 1); // var asm = new JocysCom.ClassLibrary.Configuration.AssemblyInfo(); // var path = asm.GetAppDataPath(false, "Images\\Screen_{0:yyyyMMdd_HHmmss_fff}.png", DateTime.Now); // lineBitmap.Save(path, ImageFormat.Png); Basic.GetImageBytes(ref lineBytes, lineBitmap); var prefixBytes = SettingsManager.Options.DisplayMonitorHavePixelSpaces ? ColorPrefixBytesBlanked : ColorPrefixBytes; var index = JocysCom.ClassLibrary.Text.Helper.IndexOf(lineBytes, prefixBytes); // If not found then... if (index == -1) { return; } // StatusTextBox.Text += string.Format("Prefix found"); if (SettingsManager.Options.DisplayMonitorHavePixelSpaces) { RemoveBlankPixels(lineBytes, ref lineBufferNoBlanks); } else { lineBufferNoBlanks = lineBytes; } var prefix = ColorPrefixBytes; // Skip prefix. var ms = new MemoryStream(lineBufferNoBlanks, prefix.Length, lineBufferNoBlanks.Length - prefix.Length); var br = new System.IO.BinaryReader(ms); change = ReadRgbInt(br); var messageSize = ReadRgbInt(br); var messageBytes = new byte[messageSize]; br.Read(messageBytes, 0, messageSize); message = System.Text.Encoding.UTF8.GetString(messageBytes); 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(); }
static public int Dispose(IntPtr l) { try { System.IO.BinaryReader self = (System.IO.BinaryReader)checkSelf(l); self.Dispose(); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
// 動画のバイナリをリソースからロードする処理 private static byte[] LoadVideoBinary() { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly(); Stream stream = assembly.GetManifestResourceStream("OpenBrowser.mp4"); BinaryReader reader = new System.IO.BinaryReader(stream); int len = (int)stream.Length; byte[] buf = new Byte[len]; reader.Read(buf, 0, len); reader.Dispose(); return(buf); }
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 }
public static byte[] ReadContentBytes(string fileName) { using (System.IO.FileStream file = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { System.IO.BinaryReader reader = new System.IO.BinaryReader(file); int size = Convert.ToInt32(file.Length); var result = reader.ReadBytes(size); reader.Dispose(); return(result); } }
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 = (ushort)br.ReadInt16(); br.Close(); ms.Close(); br.Dispose(); ms.Dispose(); } catch (Exception) { } }
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); } }
/* * 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> /// This method performs cleanup of resources. /// The Boolean parameter <paramref name="disposing"/> indicates whether the method is called from <see cref="IDisposable.Dispose"/> (if <paramref name="disposing"/> is true) or from the finalizer (if <paramref name="disposing"/> is false). /// Derived classes should override this method to dispose resource if needed. /// </summary> /// <param name="disposing">Flag to request disposal.</param> protected override void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { _reader.Dispose(); } disposed = true; base.Dispose(disposing); }
/// <summary> /// Image: prefix[6] + change[1] + size[1] + message_bytes /// </summary> public void CaptureTextFromPosition(out int change, out string message) { change = 0; message = null; var x = SettingsManager.Options.DisplayMonitorPositionX; var y = SettingsManager.Options.DisplayMonitorPositionY; var screen = System.Windows.Forms.Screen.PrimaryScreen; var sw = screen.Bounds.Width; var sh = screen.Bounds.Height; // Make sure take pixel pairs till the end of the line. var length = sw - x; length = length - (length % 2); // Take screenshot of the line. Basic.CaptureImage(ref lineBitmap, x, y, length, 1); Basic.GetImageBytes(ref lineBytes, lineBitmap); var prefixBytes = SettingsManager.Options.DisplayMonitorHavePixelSpaces ? ColorPrefixBytesBlanked : ColorPrefixBytes; var index = JocysCom.ClassLibrary.Text.Helper.IndexOf(lineBytes, prefixBytes); // If not found then... if (index == -1) { return; } // StatusTextBox.Text += string.Format("Prefix found"); if (SettingsManager.Options.DisplayMonitorHavePixelSpaces) { RemoveBlankPixels(lineBytes, ref lineBufferNoBlanks); } else { lineBufferNoBlanks = lineBytes; } var prefix = ColorPrefixBytes; // Skip prefix. var ms = new MemoryStream(lineBufferNoBlanks, prefix.Length, lineBufferNoBlanks.Length - prefix.Length); var br = new System.IO.BinaryReader(ms); change = ReadRgbInt(br); var messageSize = ReadRgbInt(br); var messageBytes = new byte[messageSize]; br.Read(messageBytes, 0, messageSize); message = System.Text.Encoding.UTF8.GetString(messageBytes); br.Dispose(); }
public void Dispose() { Close(); if (_bDataFile == null) { return; } lock (_lockObject) { if (_bDataFile == null) { return; } _bDataFile.Dispose(); } }
/// <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(); }
/// <summary> /// Method to get image file in actual size /// </summary> /// <param name="context">http context</param> /// <param name="stream">file stream</param> /// <returns>returns byte array</returns> private byte[] GetFile(HttpContext context, FileStream stream) { byte[] browsedFile; System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(stream); long _TotalBytes = requestedFileInfo.Length; browsedFile = binaryReader.ReadBytes((Int32)_TotalBytes); binaryReader.Close(); binaryReader.Dispose(); stream.Close(); stream.Dispose(); context.Response.Clear(); context.Response.ContentType = HTML_RESPONSE_CONTENT_TYPE; context.Response.BinaryWrite(browsedFile); context.Response.End(); return(browsedFile); }
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); }
void Response_Completed(IAsyncResult result) { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)result.AsyncState; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.EndGetResponse(result); byte[] b = null; if (request.HaveResponse) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { System.IO.Stream receiveStream = response.GetResponseStream(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(receiveStream)) { b = br.ReadBytes(500000); br.Dispose(); } } } }
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) { } }
public static byte[] FileToByteArray(string _filePath, long _startpos) { FileStream fs = null; byte[] _Buffer = null; try { fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.Read); using (TextReader tr = new StreamReader(fs)) { // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(fs); _BinaryReader.BaseStream.Position = _startpos; // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_filePath).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); // close file reader _BinaryReader.Close(); _BinaryReader.Dispose(); fs.Close(); fs.Dispose(); } } finally { if (fs != null) { fs.Dispose(); } } return(_Buffer); }
// // GET: /AdminUpload/ /// <summary> /// C#检测上传图片文件 /// </summary> /// <param name="stream">上传文件流</param> /// <param name="fileType">fileType 文件类型</param> /// <param name="fileclass">返回文件真实扩展名</param> /// <param name="DisposeStream">是否关闭当前资源</param> /// <returns></returns> public static bool IsAllowedFileExtension(System.IO.Stream stream, string[] fileType, out string fileclass, bool DisposeStream) { bool ret = false; //System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read); //System.IO.BinaryReader r = new System.IO.BinaryReader(fs); System.IO.BinaryReader r = new System.IO.BinaryReader(stream); fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { return(false); } finally { //r.Close(); //r.Dispose(); //fs.Close(); //fs.Dispose(); if (DisposeStream) { r.Close(); r.Dispose(); stream.Close(); stream.Dispose(); } } /*文件扩展名说明 * 4946/104116 txt * 7173 gif * 255216 jpg * 13780 png * 6677 bmp * 239187 txt,aspx,asp,sql * 208207 xls.doc.ppt * 6063 xml * 6033 htm,html * 4742 js * 8075 xlsx,zip,pptx,mmap,zip * 8297 rar * 01 accdb,mdb * 7790 exe,dll * 5666 psd * 255254 rdp * 10056 bt种子 * 64101 bat * 4059 sgf */ //String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" }; //纯图片 //String[] fileType = { // "7173", //gif // "255216", //jpg // "13780" //png //}; for (int i = 0; i < fileType.Length; i++) { if (fileclass == fileType[i]) { ret = true; break; } } //Response.Write(fileclass);//可以在这里输出你不知道的文件类型的扩展名 return(ret); }
private void OnDestroy() => reader?.Dispose();
public void Close() { reader.Dispose(); reader.Close(); }
/// <inheritdoc /> /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _binaryReader?.Dispose(); }
/// <summary> /// Transform an input stream using the given rule /// </summary> /// <param name="input">Input stream</param> /// <param name="output">Output stream</param> /// <param name="keepReadOpen">True if the underlying read stream should be kept open, false otherwise</param> /// <param name="keepWriteOpen">True if the underlying write stream should be kept open, false otherwise</param> /// <returns>True if the file was transformed properly, false otherwise</returns> public bool TransformStream(Stream input, Stream output, bool keepReadOpen = false, bool keepWriteOpen = false) { bool success = true; // If the sizes are wrong for the values, fail long extsize = input.Length; if ((Operation > HeaderSkipOperation.Bitswap && (extsize % 2) != 0) || (Operation > HeaderSkipOperation.Byteswap && (extsize % 4) != 0) || (Operation > HeaderSkipOperation.Bitswap && (StartOffset == null || StartOffset % 2 == 0))) { Globals.Logger.Error("The stream did not have the correct size to be transformed!"); return(false); } // Now read the proper part of the file and apply the rule BinaryWriter bw = null; BinaryReader br = null; try { Globals.Logger.User("Applying found rule to input stream"); bw = new BinaryWriter(output); br = new BinaryReader(input); // Seek to the beginning offset if (StartOffset == null) { success = false; } else if (Math.Abs((long)StartOffset) > input.Length) { success = false; } else if (StartOffset > 0) { input.Seek((long)StartOffset, SeekOrigin.Begin); } else if (StartOffset < 0) { input.Seek((long)StartOffset, SeekOrigin.End); } // Then read and apply the operation as you go if (success) { byte[] buffer = new byte[4]; int pos = 0; while (input.Position < (EndOffset ?? input.Length) && input.Position < input.Length) { byte b = br.ReadByte(); switch (Operation) { case HeaderSkipOperation.Bitswap: // http://stackoverflow.com/questions/3587826/is-there-a-built-in-function-to-reverse-bit-order uint r = b; int s = 7; for (b >>= 1; b != 0; b >>= 1) { r <<= 1; r |= (byte)(b & 1); s--; } r <<= s; buffer[pos] = (byte)r; break; case HeaderSkipOperation.Byteswap: if (pos % 2 == 1) { buffer[pos - 1] = b; } if (pos % 2 == 0) { buffer[pos + 1] = b; } break; case HeaderSkipOperation.Wordswap: buffer[3 - pos] = b; break; case HeaderSkipOperation.WordByteswap: buffer[(pos + 2) % 4] = b; break; case HeaderSkipOperation.None: default: buffer[pos] = b; break; } // Set the buffer position to default write to pos = (pos + 1) % 4; // If we filled a buffer, flush to the stream if (pos == 0) { bw.Write(buffer); bw.Flush(); buffer = new byte[4]; } } // If there's anything more in the buffer, write only the left bits for (int i = 0; i < pos; i++) { bw.Write(buffer[i]); } } } catch (Exception ex) { Globals.Logger.Error(ex.ToString()); return(false); } finally { // If we're not keeping the read stream open, dispose of the binary reader if (!keepReadOpen) { br?.Dispose(); } // If we're not keeping the write stream open, dispose of the binary reader if (!keepWriteOpen) { bw?.Dispose(); } } return(success); }
public Result Txn249999(ClientInfo ci, RequestInfo ri, DbConnections db, ref Log lg) { Result res = new Result(); try { object[] param = new object[1]; string ViewName = ""; Hashtable colindex = new Hashtable(); string query = ""; if (Static.ToInt(ri.ReceivedParam[1]) == 0) { Excel.Application xlsm = new Excel.Application(); Excel.Workbook xlsWorkBook = xlsm.Workbooks.Open(@Static.ToStr(ri.ReceivedParam[0]), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet xlsWorkSheet = xlsWorkBook.Worksheets[1]; ViewName = xlsWorkSheet.Name; for (int i = 1; i <= xlsWorkSheet.UsedRange.Columns.Count; i++) { if (!colindex.ContainsKey(xlsWorkSheet.Cells[1, i].Value.ToString())) { colindex.Add(xlsWorkSheet.Cells[1, i].Value.ToString(), i); } else { colindex.Clear(); res.ResultNo = 9110146; res.ResultDesc = string.Format("Тайлангын загвар алдаатай байна. {0} талбар өмнө нь үүссэн байна.", xlsWorkSheet.Cells[1, i].Value); return(res); } } res = IPos.DB.Main.DB202351(db, Static.ToStr(ViewName)); if (res.ResultNo != 0) { colindex.Clear(); return(res); } object[] obj = new object[2]; obj[0] = colindex; obj[1] = ViewName; res.Param = obj; } else { int rowindex = 2; Excel.Application xlsm = new Excel.Application(); Excel.Workbook xlsWorkBook = xlsm.Workbooks.Open(@Static.ToStr(ri.ReceivedParam[0]), 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); Excel.Worksheet xlsWorkSheet = xlsWorkBook.Worksheets[1]; ViewName = xlsWorkSheet.Name; StringBuilder sb = new StringBuilder(); object[] prop = (object[])ri.ReceivedParam[2]; bool isfirst = false; bool iswhere = false; if (prop.Count() > 0) { for (int i = 0; i < prop.Count() / 3; i = i + 3) { if (prop[i + 2] != null && prop[i + 2] != "") { if (isfirst == false) { if (Static.ToStr(prop[i + 1]).ToUpper() == "LIKE") { sb.Append(Static.ToStr(prop[i])); sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1]))); sb.Append(string.Format("'{0}%'", Static.ToStr(prop[i + 2]))); isfirst = true; } else { sb.Append(Static.ToStr(prop[i])); sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1]))); sb.Append(Static.ToStr(prop[i + 2])); isfirst = true; } } else { if (Static.ToStr(prop[i + 1]).ToUpper() == "LIKE") { sb.Append(" and "); sb.Append(Static.ToStr(prop[i])); sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1]))); sb.Append(string.Format("'{0}%'", Static.ToStr(prop[i + 2]))); isfirst = true; } else { sb.Append(" and "); sb.Append(Static.ToStr(prop[i])); sb.Append(string.Format(" {0} ", Static.ToStr(prop[i + 1]))); sb.Append(Static.ToStr(prop[i + 2])); iswhere = true; } } } } if (isfirst == true || iswhere == true) { query = string.Format("select * from {0} where {1}", ViewName, sb.ToString()); } else { query = string.Format("select * from {0}", ViewName); } } else { query = string.Format("select * from {0}", ViewName); } res = db.ExecuteQuery("core", query, enumCommandType.SELECT, "Txn249999", null); if (res.ResultNo != 0) { return(res); } colindex = (Hashtable)ri.ReceivedParam[3]; foreach (DataRow row in res.Data.Tables[0].Rows) { foreach (DictionaryEntry fieldname in colindex) { xlsWorkSheet.Cells[rowindex, Convert.ToInt32(fieldname.Value)].Value = row[fieldname.Key.ToString()]; } rowindex++; } string temp = Path.GetTempPath(); string filepath = string.Format(@temp + @"rep{0}.xlsm", DateTime.Now.Ticks); xlsWorkBook.SaveCopyAs(filepath); byte[] _Buffer = null; System.IO.FileStream _FileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); long _TotalBytes = new System.IO.FileInfo(@Static.ToStr(ri.ReceivedParam[0])).Length; _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); param[0] = _Buffer; _FileStream.Dispose(); _FileStream.Close(); _BinaryReader.Dispose(); _BinaryReader.Close(); colindex.Clear(); Result result = new Result(); result.Param = param; return(result); } return(res); } catch (Exception ex) { res.ResultNo = 9110002; res.ResultDesc = "Програм руу нэвтрэхэд алдаа гарлаа" + ex.Message; EServ.Shared.Static.WriteToLogFile("Error.log", ex.Message + ex.Source + ex.StackTrace); return(res); } finally { lg.item.Desc = "Excel тайлангийн жагсаалт авах"; } }
/// <summary> /// Retrieve file information for a single torrent GZ file /// </summary> /// <returns>Populated DatItem object if success, empty one on error</returns> public BaseFile GetTorrentGZFileInfo() { // Check for the file existing first if (!File.Exists(_filename)) { return(null); } string datum = Path.GetFileName(_filename).ToLowerInvariant(); long filesize = new FileInfo(_filename).Length; // If we have the romba depot files, just skip them gracefully if (datum == ".romba_size" || datum == ".romba_size.backup") { Globals.Logger.Verbose("Romba depot file found, skipping: {0}", _filename); return(null); } // Check if the name is the right length if (!Regex.IsMatch(datum, @"^[0-9a-f]{" + Constants.SHA1Length + @"}\.gz")) // TODO: When updating to SHA-256, this needs to update to Constants.SHA256Length { Globals.Logger.Warning("Non SHA-1 filename found, skipping: '{0}'", Path.GetFullPath(_filename)); return(null); } // Check if the file is at least the minimum length if (filesize < 40 /* bytes */) { Globals.Logger.Warning("Possibly corrupt file '{0}' with size {1}", Path.GetFullPath(_filename), Utilities.GetBytesReadable(filesize)); return(null); } // Get the Romba-specific header data byte[] header; // Get preamble header for checking byte[] headermd5; // MD5 byte[] headercrc; // CRC ulong headersz; // Int64 size BinaryReader br = new BinaryReader(Utilities.TryOpenRead(_filename)); header = br.ReadBytes(12); headermd5 = br.ReadBytes(16); headercrc = br.ReadBytes(4); headersz = br.ReadUInt64(); br.Dispose(); // If the header is not correct, return a blank rom bool correct = true; for (int i = 0; i < header.Length; i++) { // This is a temp fix to ignore the modification time and OS until romba can be fixed if (i == 4 || i == 5 || i == 6 || i == 7 || i == 9) { continue; } correct &= (header[i] == Constants.TorrentGZHeader[i]); } if (!correct) { return(null); } // Now convert the data and get the right position long extractedsize = (long)headersz; BaseFile baseFile = new BaseFile { Filename = Path.GetFileNameWithoutExtension(_filename).ToLowerInvariant(), Size = extractedsize, CRC = headercrc, MD5 = headermd5, SHA1 = Utilities.StringToByteArray(Path.GetFileNameWithoutExtension(_filename)), // TODO: When updating to SHA-256, this needs to update to SHA256 Parent = Path.GetFileNameWithoutExtension(_filename).ToLowerInvariant(), }; return(baseFile); }
public void ImportHeightmap() { var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw", "r16", "bmp" }) }; var paths = StandaloneFileBrowser.OpenFilePanel("Import heightmap", DefaultPath, extensions, false); if (paths == null || paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapResolution; int w = ScmapEditor.Current.Teren.terrainData.heightmapResolution; ScmapEditor.GetAllHeights(ref beginHeights); Undo.RegisterUndo(new UndoHistory.HistoryTerrainHeight(), new UndoHistory.HistoryTerrainHeight.TerrainHeightHistoryParameter(beginHeights)); float[,] data = new float[h, w]; //float[,] old = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); if (paths[0].ToLower().EndsWith("bmp")) { BMPLoader loader = new BMPLoader(); BMPImage img = loader.LoadBMP(paths[0]); Debug.Log(img.info.compressionMethod + ", " + img.info.nBitsPerPixel + ", " + img.rMask + ", " + img.imageData[0].r); Texture2D ImportedImage = img.ToTexture2D(); if (ImportedImage.width != h || ImportedImage.height != w) { Debug.Log("Wrong size"); TextureScale.Bilinear(ImportedImage, h, w); ImportedImage.Apply(false); } Color[] ImportedColors = ImportedImage.GetPixels(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y, x] = (float)ImportedColors[x + y * w].r / 0.567f; // 0.58 } } } else { using (var file = System.IO.File.OpenRead(paths[0])) using (var reader = new System.IO.BinaryReader(file)) { long CheckValue = 2; CheckValue *= (long)(w); CheckValue *= (long)(h); long FileLength = file.Length; if (FileLength != CheckValue) { reader.Dispose(); file.Dispose(); GenericPopup.ShowPopup(GenericPopup.PopupTypes.Error, "Error", "Selected heightmap is in wrong size.\nIs: " + FileLength + "B, should be: " + CheckValue + "B", "OK", null); return; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float v = (float)(reader.ReadUInt16() / ScmapEditor.HeightResize); data[h - (y + 1), x] = v; } } } } //ScmapEditor.Current.Teren.terrainData.SetHeights(0, 0, data); ScmapEditor.SetAllHeights(data); RegenerateMaps(); OnTerrainChanged(); EnvPaths.SetLastPath(ExportPathKey, Path.GetDirectoryName(paths[0])); GenericInfoPopup.ShowInfo("Heightmap import success!\n" + Path.GetFileName(paths[0])); if (ScmapEditor.IsOverMinMaxDistance()) { GenericPopup.ShowPopup(GenericPopup.PopupTypes.TriButton, "Importing heightmap", "Distance between lowest and highest point is higher than 50.\nClamp it?", "Clamp Top", ClampTop, "Clamp Bottom", ClampBottom, "Ignore", null); } }