public bool Load(string path) { System.IO.FileStream fs = null; try { fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch(System.IO.FileNotFoundException e) { return false; } var br = new System.IO.BinaryReader(fs); var buf = new byte[1024]; if (br.Read(buf, 0, 8) != 8) { fs.Dispose(); br.Dispose(); return false; } // png Header 89 50 4E 47 0D 0A 1A 0A if (buf[0] == 0x89 && buf[1] == 0x50 && buf[2] == 0x4E && buf[3] == 0x47 && buf[4] == 0x0D && buf[5] == 0x0A && buf[6] == 0x1A && buf[7] == 0x0A) { if (br.Read(buf, 0, 25) != 25) { fs.Dispose(); br.Dispose(); return false; } var width = new byte[] { buf[11], buf[10], buf[9], buf[8] }; var height = new byte[] { buf[15], buf[14], buf[13], buf[12] }; Width = BitConverter.ToInt32(width, 0); Height = BitConverter.ToInt32(height, 0); } else { fs.Dispose(); br.Dispose(); return false; } fs.Dispose(); br.Dispose(); return true; }
public bool Load(string path) { System.IO.FileStream fs = null; try { fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch (System.IO.FileNotFoundException e) { return(false); } var br = new System.IO.BinaryReader(fs); var buf = new byte[1024]; if (br.Read(buf, 0, 8) != 8) { fs.Dispose(); br.Dispose(); return(false); } // png Header 89 50 4E 47 0D 0A 1A 0A if (buf[0] == 0x89 && buf[1] == 0x50 && buf[2] == 0x4E && buf[3] == 0x47 && buf[4] == 0x0D && buf[5] == 0x0A && buf[6] == 0x1A && buf[7] == 0x0A) { if (br.Read(buf, 0, 25) != 25) { fs.Dispose(); br.Dispose(); return(false); } var width = new byte[] { buf[11], buf[10], buf[9], buf[8] }; var height = new byte[] { buf[15], buf[14], buf[13], buf[12] }; Width = BitConverter.ToInt32(width, 0); Height = BitConverter.ToInt32(height, 0); } else { fs.Dispose(); br.Dispose(); return(false); } fs.Dispose(); br.Dispose(); return(true); }
public bool Load(string path) { System.IO.FileStream fs = null; try { fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch (System.IO.FileNotFoundException e) { return(false); } var br = new System.IO.BinaryReader(fs); var buf = new byte[1024]; if (br.Read(buf, 0, 8) != 8) { fs.Dispose(); br.Dispose(); return(false); } var version = BitConverter.ToInt32(buf, 0); if (version == 2) { Scale = BitConverter.ToSingle(buf, 4); fs.Dispose(); br.Dispose(); return(false); } if (version == 3) { fs.Seek(-4, System.IO.SeekOrigin.End); if (br.Read(buf, 0, 4) == 4) { Scale = BitConverter.ToSingle(buf, 0); } else { fs.Dispose(); br.Dispose(); return(false); } } fs.Dispose(); br.Dispose(); return(true); }
/// <summary> /// Checks KOM file headers and returns the version of kom it is. An return of 0 is an Error. /// </summary> private static int GetHeaderVersion(string komfile) { int ret = 0; System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(System.Windows.Forms.Application.StartupPath + "\\koms\\" + komfile), System.Text.Encoding.ASCII); byte[] headerbuffer = new byte[27]; // 27 is the size of the header string denoting the KOM file version number. int offset = 0; reader.Read(headerbuffer, offset, 27); string headerstring = System.Text.Encoding.UTF8.GetString(headerbuffer); reader.Dispose(); foreach (var komplugin in komplugins) { // get version of kom file for unpacking it. if (komplugin.KOMHeaderString == string.Empty) { // skip this plugin it does not implement an packer or unpacker. continue; } if (headerstring == komplugin.KOMHeaderString) { ret = komplugin.SupportedKOMVersion; } } return(ret); }
// Stops replay and releases resources private static void Cleanup() { if (tx_sock != null) { tx_sock.Close(); } if (BinaryReader != null) { BinaryReader.Close(); } if (FileStream != null) { FileStream.Close(); } if (BinaryReader != null) { BinaryReader.Dispose(); } if (FileStream != null) { FileStream.Dispose(); } TotalFileSizeBytes = 0; Replay_Status = ReplayStatus.Disconnected; }
public void Unpack(string in_path, string out_path, string KOMFileName) { System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(in_path), System.Text.Encoding.ASCII); reader.BaseStream.Position += 52; int entry_count = (int)reader.ReadUInt64(); // trying to understand this crap... This is where it starts to fail // for KOM V4 on Elsword's current data036.kom. int compressed = reader.ReadInt32(); int file_time = reader.ReadInt32(); int xml_size = reader.ReadInt32(); byte[] xmldatabuffer = reader.ReadBytes(xml_size); Els_kom_Core.Classes.KOMStream kOMStream = new Els_kom_Core.Classes.KOMStream(); kOMStream.DecryptCRCXml(compressed, ref xmldatabuffer, xml_size, System.Text.Encoding.ASCII); string xmldata = System.Text.Encoding.ASCII.GetString(xmldatabuffer); try { System.Collections.Generic.List <Els_kom_Core.Classes.EntryVer> entries = kOMStream.Make_entries_v4(xmldata, entry_count); foreach (var entry in entries) { // we iterate through every entry here and unpack the data. kOMStream.WriteOutput(reader, out_path, entry, SupportedKOMVersion); } } catch (System.Xml.XmlException) { throw new Els_kom_Core.Classes.UnpackingError("failure with xml entry data reading..."); } kOMStream.Dispose(); reader.Dispose(); }
public static void Dispose(System.IO.BinaryReader reader) { #if NETFX_CORE reader.Dispose(); #else reader.Close(); #endif }
public void Dispose() { if (mReader != null) { mReader.Close(); mReader.Dispose(); mReader = null; } if (mWriter != null) { mWriter.Close(); mWriter.Dispose(); mWriter = null; } if (mStream != null) { mStream.Close(); mStream.Dispose(); mStream = null; } }
private void button1_Click(object sender, EventArgs e) { // L197 binary reader instance, object System.IO.BinaryReader BR = new System.IO.BinaryReader(System.IO.File.OpenRead("C:\\Users\\judas\\HP DV 6000 source\\repos\\New test folder\\Test byte reader2.txt")); // reads two byte in hexadecimal little endian MessageBox.Show(BR.ReadUInt16().ToString("X")); // L197 use Dispose to delete it BR.Dispose(); // L197 initialize MyClass constructor MyClass MC = new MyClass(); }
/// <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); }
public static async Task AddImageFromUrl(string url, string imageName) { System.Net.HttpWebRequest request = null; byte[] b = null; name = imageName; request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "GET"; using (var response = (System.Net.HttpWebResponse) await request.GetResponseAsync()) { 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); if (b != null) { if (!Images.ContainsKey(name)) { // hold image byte[] image = new byte[b.Length]; image = b; Images.Add(imageName, b); // Debug.WriteLine("MAP SIZE: " + getImages.Count); b = null; } } br.Dispose(); } } } } }
public void Unpack(string in_path, string out_path, string KOMFileName) { System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(in_path), System.Text.Encoding.ASCII); reader.BaseStream.Position = 52; Els_kom_Core.Classes.KOMStream kOMStream = new Els_kom_Core.Classes.KOMStream(); kOMStream.ReadInFile(reader, out int entry_count); // without this dummy read the entry instances would not get the correct // data leading to an crash when tring to make an file with the entry name in the output path. kOMStream.ReadInFile(reader, out int size); System.Collections.Generic.List <Els_kom_Core.Classes.EntryVer> entries = kOMStream.Make_entries_v2(entry_count, reader); foreach (var entry in entries) { // we iterate through every entry here and unpack the data. kOMStream.WriteOutput(reader, out_path, entry, SupportedKOMVersion); } kOMStream.Dispose(); reader.Dispose(); }
static int _m_Dispose(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.IO.BinaryReader gen_to_be_invoked = (System.IO.BinaryReader)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Dispose( ); return(0); } } catch (System.Exception gen_e) { return(LuaAPI.luaL_error(L, "c# exception:" + gen_e)); } }
bool GetPointCacheSourceStatistic(string path, ref string name, ref int vertCount, ref int framesCount, ref string message) { string extension = System.IO.Path.GetExtension(path); if (extension == ".obj") { MeshSequenceInfo msi = new MeshSequenceInfo(path, MeshSequenceInfo.SortModeEnum.ByNumber); name = msi.SequenceName; framesCount = msi.infos.Length; vertCount = 0; ObjData.GetObjInfo(path, ref vertCount); return(true); } else { name = (new System.IO.FileInfo(path)).Name; System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open); System.IO.BinaryReader binReader = new System.IO.BinaryReader(fs); binReader.ReadChars(12); binReader.ReadInt32(); vertCount = binReader.ReadInt32(); binReader.ReadSingle(); //start frame binReader.ReadSingle(); //sample rate framesCount = binReader.ReadInt32(); #if UNITY_WSA binReader.Dispose(); fs.Dispose(); #else binReader.Close(); fs.Close(); #endif return(vertCount > 0 && framesCount > 0); } }
public void Unpack(string in_path, string out_path, string KOMFileName) { System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.OpenRead(in_path), System.Text.Encoding.ASCII); reader.BaseStream.Position += 52; int entry_count = (int)reader.ReadUInt64(); reader.BaseStream.Position += 4; int file_time = reader.ReadInt32(); int xml_size = reader.ReadInt32(); byte[] xmldatabuffer = reader.ReadBytes(xml_size); string xmldata = System.Text.Encoding.ASCII.GetString(xmldatabuffer); Els_kom_Core.Classes.KOMStream kOMStream = new Els_kom_Core.Classes.KOMStream(); System.Collections.Generic.List <Els_kom_Core.Classes.EntryVer> entries = kOMStream.Make_entries_v3(xmldata, entry_count); foreach (var entry in entries) { // we iterate through every entry here and unpack the data. kOMStream.WriteOutput(reader, out_path, entry, SupportedKOMVersion); } kOMStream.Dispose(); reader.Dispose(); }
private static string LoadPasswordFromFile(string fileName) { string value = ""; List <byte> byteList = new List <byte>(); System.IO.FileStream stream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); while (reader.PeekChar() != -1) { byteList.Add(reader.ReadByte()); } reader.Close(); reader.Dispose(); stream.Close(); stream.Dispose(); value = Encoding.UTF8.GetString(byteList.ToArray()); value = value.Replace(Environment.NewLine, ""); value = value.Replace(" ", ""); value = DESManager.Decrypt(value); value = DESManager.Decrypt(value); value = DESManager.Decrypt(value); return(value); }
/// <summary> /// Parse the form data within the stream, including any uploaded file data. /// </summary> /// <param name="timeout">The maximum time in milliseconds to wait for the end of the header data; -1 wait Indefinitely</param> /// <returns>The http form model parsed from the stream; else null.</returns> public Nequeo.Net.Http.Common.HttpFormModel ParseForm(long timeout = -1) { System.IO.BinaryReader reader = null; try { // Create the reader. reader = new System.IO.BinaryReader(Input, Encoding.Default, true); // Return the result. return(Nequeo.Net.Http.Utility.ParseForm(reader, timeout)); } catch (Exception) { throw; } finally { if (reader != null) { reader.Dispose(); } } }
private bool _LeeSLTBinario(String FicheroSLT) { /*****Binary STL * * Because ASCII STL files can become very large, a binary version of STL exists. A binary STL file has an 80-character header (which is generally ignored, but should never begin with * "solid" because that will lead most software to assume that this is an ASCII STL file). Following the header is a 4-byte unsigned integer indicating the number of triangular facets * in the file. Following that is data describing each triangle in turn. The file simply ends after the last triangle. * * Each triangle is described by twelve 32-bit doubleing-point numbers: three for the normal and then three for the X/Y/Z coordinate of each vertex – just as with the ASCII version of STL. * After these follows a 2-byte ("short") unsigned integer that is the "attribute byte count" – in the standard format, this should be zero because most software does not understand anything else. * * doubleing-point numbers are represented as IEEE doubleing-point numbers and are assumed to be little-endian, although this is not stated in documentation. * * UINT8[80] – Header * UINT32 – Number of triangles * * foreach triangle * REAL32[3] – Normal vector * REAL32[3] – Vertex 1 * REAL32[3] – Vertex 2 * REAL32[3] – Vertex 3 * UINT16 – Attribute byte count * end */ bool Res = true; System.IO.StreamReader SR = new System.IO.StreamReader(FicheroSLT, Encoding.ASCII); //Evalua si es binario o ASCII string LineaSLT = SR.ReadLine(); LineaSLT = LineaSLT.TrimStart(new char[2] { ' ', '\t' }); SR.Close(); SR.Dispose(); if (!LineaSLT.StartsWith("solid ")) { System.IO.FileStream FS = new System.IO.FileStream(FicheroSLT, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader BR = new System.IO.BinaryReader(FS); //Cabecera UINT8[80] – Header for (int i = 0; i < 80; i++) { char TempChar = BR.ReadChar(); if (TempChar != '\0') { Nombre += TempChar; } } //Número de triángulos UINT32 – Number of triangles UInt32 NumTriangulos = BR.ReadUInt32(); if (NumTriangulos > 0) { LoopSLT TempLoop = new LoopSLT(); FacetSLT TempFacet = new FacetSLT(); for (UInt32 Ui = 0; Ui < NumTriangulos; Ui++) { //Vector Normal REAL32[3] – Normal vector TempFacet._Normal = new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle())); //REAL32[3] – Vertex 1 TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle()))); //REAL32[3] – Vertex 2 TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle()))); //REAL32[3] – Vertex 3 TempLoop.Vertices.Add(new VertexSLT(Round(BR.ReadSingle()), Round(BR.ReadSingle()), Round(BR.ReadSingle()))); TempLoop.ActualizaBoundingZ(); TempFacet._Loops.Add(TempLoop); //Attribute byte count TempFacet._Attribute = BR.ReadUInt16(); if (TempFacet.EsValido()) { _Facets.Add(TempFacet); } else { Res = false; Fallos.Add("Lectura SLT Binario: Faceta no válida"); } TempLoop = new LoopSLT(); TempFacet = new FacetSLT(); } } else { Res = false; Fallos.Add("Lectura SLT Binario: Número de triángulos nulo o igual a 0"); } BR.Close(); FS.Close(); BR.Dispose(); FS.Dispose(); } else { Res = false; Fallos.Add("Lectura SLT Binario: El Fichero comienza por 'solid '"); } return(Res); }
public bool Load(string path) { System.IO.FileStream fs = null; if (!System.IO.File.Exists(path)) { return(false); } try { fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); } catch (System.IO.FileNotFoundException e) { return(false); } var br = new System.IO.BinaryReader(fs); var buf = new byte[1024]; // ヘッダー部分読み込み if (br.Read(buf, 0, 30) != 30) { fs.Dispose(); br.Dispose(); return(false); } // png Header 89 50 4E 47 0D 0A 1A 0A if (buf[0] == 0x89 && buf[1] == 0x50 && buf[2] == 0x4E && buf[3] == 0x47 && buf[4] == 0x0D && buf[5] == 0x0A && buf[6] == 0x1A && buf[7] == 0x0A) { var width = new byte[] { buf[19], buf[18], buf[17], buf[16] }; var height = new byte[] { buf[23], buf[22], buf[21], buf[20] }; Width = BitConverter.ToInt32(width, 0); Height = BitConverter.ToInt32(height, 0); } // tga か拡張子で判別 else if (path.Contains(".tga") == true) { var width = new byte[] { buf[12], buf[13], 0, 0 }; var height = new byte[] { buf[14], buf[15], 0, 0 }; Width = BitConverter.ToInt32(width, 0); Height = BitConverter.ToInt32(height, 0); } else { // 知らない拡張子なので弾く fs.Dispose(); br.Dispose(); return(false); } fs.Dispose(); br.Dispose(); return(true); }
private void btnChooseFile_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".data"; dlg.Filter = "Frame data (*.data)|*.data"; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { frameList.Clear(); // Open document string filename = dlg.FileName; using (System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.Open(filename, System.IO.FileMode.Open))) { while (br.BaseStream.Position < br.BaseStream.Length) { //deserialises and reads the binary file DateTime date = new DateTime(); date = DateTime.FromBinary(br.ReadInt64()); // Console.WriteLine(date.ToString()); Int32 stimCode = br.ReadInt32(); Int32 nextBlock = br.ReadInt32(); byte[] frameData = br.ReadBytes(nextBlock); Leap.Frame newFrame = new Leap.Frame(); newFrame.Deserialize(frameData); if (stimCode == 5443) { Debug.WriteLine("5443 detected: " + newFrame.Id); } frameList.Add(newFrame); //Console.WriteLine(newFrame.CurrentFramesPerSecond); } br.Close(); br.Dispose(); } /* WRITE CODE HERE TO EXTRACT DATA FROM FILE foreach (Leap.Frame frame in frameList) { //Console.WriteLine(frame.Id); } */ } }
/*public static void mapDecypher(System.IO.BinaryReader br, int headerOffset, int id) * { * /* * 09 1115 used in $C0/591A (DC2D84,((00:1115 & 0x3F (6 bits)) * 4) + DC/2E24) First [4bpp 8x8] Graphics load * .. .... used in $C0/596A (DC2D84,(Invert_Bytes((00:1115..16 & 0FC0) * 4) * 4) + DC/2E24) Second [4bpp 8x8] Graphics load * 0A 1116 used in $C0/59D7 (DC2D84,((00:1116..7 & 03F0)/4) + DC/2E24) Third [4bpp 8x8] Graphics load * 0B 1117 used in $C0/5A45 (DC0000,((00:1117 & #$FC) / 2) + DC/0024) [2bpp 8x8] Graphics load * * 0C 1118 used in $C0/5877 (CB0000,(((00:1118 & 0x03FF) - 1) * 2) + CB...CC.../0000???) [unheaded Type02] (I.e. CC/344B) -> Bytemap decompressed in 7F:0000 * 0D 1119 used in $C0/588D (if (((00:1119 & 0x0FFC) / 4) - 1) == 0xFFFF => 0-> 7F0000:7F0FFF) [unheaded Type02] -> Bytemap ???? decompressed in 7F:1000 ???? * 0E 111A used in $C0/58B6 (CB0000,(((00:111A & 0x3FF0)/16) - 1) * 2) + CB...CC.../0000???) [unheaded Type02] (I.e. CC/344B) -> Bytemap ???? decompressed in 7F:2000 ???? * 0F 111B " * * 16 1122 Used in $C0/58DB (Sent 0x100 bytes C3BB00,([17] * 0x0100 [16]) (i.e. C3:C400) -> to 00:0C00 [Palette]) * // * * int offset = 0; * br.BaseStream.Position = 0x0E9C00 + headerOffset + (id * 0x1A); * List<Byte> mapDescriptors = br.ReadBytes(0x1A).ToList(); * * * * br.BaseStream.Position = 0x03BB00 + headerOffset + (mapDescriptors[0x16] + mapDescriptors[0x17] * 0x0100); * Byte[] bytePal = br.ReadBytes(0x0100); * Color[] palette = new Color[0x0100]; * for (int i = 0; i < 0x0100; i += 2) * { * int color = bytePal[i] + bytePal[i + 1] * 0x0100; * int r = ((color / 1) % 32) * 8; * int g = ((color / 32) % 32) * 8; * int b = ((color / 1024) % 32) * 8; * r = r + r / 32; * g = g + g / 32; * b = b + b / 32; * * palette[i] = Color.FromArgb(r, g, b); * } * * br.BaseStream.Position = 0x1C2D84 + headerOffset + ((mapDescriptors[0x09] & 0x3F) * 4); * offset = br.ReadByte() + (br.ReadByte() * 0x0100) + (br.ReadByte() * 0x010000) + 0x1C2E24 + headerOffset; * br.BaseStream.Position = offset; * Bitmap firstBitmap = Transformations.transform4b(br.ReadBytes(0x2000).ToList(), 0, 0x2000); * ManageBMP.exportBPM("firstBitmap.png", firstBitmap, palette); * * br.BaseStream.Position = 0x1C2D84 + headerOffset + ((((mapDescriptors[0x09] & 0xC0) / 4) + (mapDescriptors[0x0A] & 0x0F)) * 4); * offset = br.ReadByte() + (br.ReadByte() * 0x0100) + (br.ReadByte() * 0x010000) + 0x1C2E24 + headerOffset; * br.BaseStream.Position = offset; * Bitmap secondBitmap = Transformations.transform4b(br.ReadBytes(0x2000).ToList(), 0, 0x2000); * ManageBMP.exportBPM("secondBitmap.png", secondBitmap, palette); * * br.BaseStream.Position = 0x1C2D84 + headerOffset + (((mapDescriptors[0x0A] + (mapDescriptors[0x0B] * 0x0100)) & 0x03F0) / 4); * offset = br.ReadByte() + (br.ReadByte() * 0x0100) + (br.ReadByte() * 0x010000) + 0x1C2E24 + headerOffset; * br.BaseStream.Position = offset; * Bitmap thirdBitmap = Transformations.transform4b(br.ReadBytes(0x2000).ToList(), 0, 0x2000); * ManageBMP.exportBPM("thirdBitmap.png", thirdBitmap, palette); * * br.BaseStream.Position = 0x1C0000 + headerOffset + ((mapDescriptors[0x0B] & 0xFC) / 2); * offset = br.ReadByte() + (br.ReadByte() * 0x0100) + 0x1C0024 + headerOffset; * br.BaseStream.Position = offset; * Bitmap forthBitmap = Transformations.transform2bpp(br.ReadBytes(0x2000).ToList(), 0, 0x1000); * ManageBMP.exportBPM("forthBitmap.png", forthBitmap, Palettes.palette2b); * } */ public static void editSRM() { System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.Filter = "SRM File|*.srm"; openFileDialog.Title = "Choose a file"; /* Show the Dialog */ if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (openFileDialog.FileName != "") { System.IO.FileStream fs = new System.IO.FileStream(openFileDialog.FileName, System.IO.FileMode.Open); System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs, new UnicodeEncoding()); System.IO.BinaryReader br = new System.IO.BinaryReader(fs, new UnicodeEncoding()); // Compare checksum int accumulator = 0; //int currrentChecksum = 0; // Edit items bw.BaseStream.Position = 0x0140; for (int i = 0; i < 0x100; i++) { bw.BaseStream.WriteByte(BitConverter.GetBytes(i)[0]); } for (int i = 0; i < 0x100; i++) { bw.BaseStream.WriteByte(0x08); } br.BaseStream.Position = 0x0000; for (int i = 0; i < 0x300; i++) { accumulator += br.ReadByte() + br.ReadByte() * 0x0100; if (accumulator > 0xFFFF) { accumulator -= 0xFFFF; // or(0x010000) } } /* * FFVI * * for(int i = 0 ; i < 0x09FE ; i++) { * accumulator += br.ReadByte() + br.ReadByte() * 0x0100; * if (accumulator > 0xFFFF) accumulator -= 0xFFFF; // or(0x010000) * } * * bw.BaseStream.Position = 0x09FE; * bw.BaseStream.WriteByte(BitConverter.GetBytes(accumulator)[0]); * bw.BaseStream.WriteByte(BitConverter.GetBytes(accumulator)[1]); */ bw.BaseStream.Position = 0x1FF0; //currrentChecksum = br.ReadByte() + br.ReadByte() * 0x0100; //System.Windows.Forms.MessageBox.Show(currrentChecksum.ToString("X4"), accumulator.ToString("X4")); bw.BaseStream.WriteByte(BitConverter.GetBytes(accumulator)[0]); bw.BaseStream.WriteByte(BitConverter.GetBytes(accumulator)[1]); bw.Close(); bw.Dispose(); br.Close(); br.Dispose(); fs.Close(); fs.Dispose(); } } openFileDialog.Dispose(); openFileDialog = null; }
/// <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); }
void UpdatePreview(string path) { if (!System.IO.File.Exists(path)) { return; } try { // ミニ窓用のデータ読み込み // 拡張子で png 判定 if (binding.GetAbsolutePath().Contains(".png") == true) { Bitmap srcbmp = new Bitmap(binding.GetAbsolutePath()); lbl_info.Text = "" + srcbmp.Width + "x" + srcbmp.Height + " " + srcbmp.PixelFormat.ToString(); int height = (128 <= srcbmp.Height) ? 128 : srcbmp.Height; int width = srcbmp.Width * height / srcbmp.Height; Bitmap dstbmp = new Bitmap(width, height); Graphics g = Graphics.FromImage(dstbmp); // 市松模様を描画 for (int i = 0; i < height / 16; i++) { for (int j = 0; j < width / 16; j++) { g.FillRectangle(Brushes.White, j * 16, i * 16, 8, 8); g.FillRectangle(Brushes.LightGray, j * 16, i * 16 + 8, 8, 8); g.FillRectangle(Brushes.LightGray, j * 16 + 8, i * 16, 8, 8); g.FillRectangle(Brushes.White, j * 16 + 8, i * 16 + 8, 8, 8); } } // 画像を描画 g.DrawImage(srcbmp, 0, 0, width, height); g.Dispose(); pic_preview.Width = width; pic_preview.Height = height; pic_preview.Image = dstbmp; srcbmp.Dispose(); //this.Height = 40 + height; } // 拡張子で tga 判定 else if (binding.GetAbsolutePath().Contains(".tga") == true) { // ファイルを開いてバイナリで読み込み System.IO.FileStream fs = null; fs = System.IO.File.Open( binding.GetAbsolutePath(), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); var br = new System.IO.BinaryReader(fs); // ヘッダー部読み込み var header = new byte[18]; br.Read(header, 0, 18); // 画像の大きさ取得 int width = header[12] + header[13] * 256; int height = header[14] + header[15] * 256; int format = header[16]; int color_step = 4; if (format == 24) { color_step = 3; } // 格納されているカラーデータのサイズ int color_size = (width * height) * color_step; // バイナリからカラーデータ読み込み byte[] pixel_data = new byte[color_size]; br.Read(pixel_data, 0, color_size); // もう使わないので削除 fs.Dispose(); br.Dispose(); // Bitmap 作成 Bitmap bmp = new Bitmap(width, height); int y_step = 1; int x_step = 1; if (height > 128) { y_step = height / 128; } if (width > 128) { x_step = width / 128; } // ピクセル単位で読み込み for (int y = 0; y < height; y += y_step) { for (int x = 0; x < width; x += x_step) { int by = y * width; int bx = x; int base_i = (by + bx) * color_step; Color color = Color.FromArgb( (color_step == 4) ? pixel_data[base_i + 3] : 255, pixel_data[base_i + 2], pixel_data[base_i + 1], pixel_data[base_i + 0] ); bmp.SetPixel(x / x_step, ((height - 1) - y) / y_step, color); } } // プレビュー用データを設定 lbl_info.Text = "" + bmp.Width + "x" + bmp.Height + " " + ((format == 32) ? "Format32bpp" : "Format24bpp"); pic_preview.Width = width; pic_preview.Height = height; pic_preview.Image = bmp; } } catch (Exception e) { if (path == null) { path = string.Empty; } System.IO.File.WriteAllText("error_image.txt", path + "\n" + e.ToString()); pic_preview.Image = null; } }
private void ListenThreadEntrypoint() { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.BinaryReader reader = new System.IO.BinaryReader(ms); try { this.ClientConnection = new TcpClient(this.Host, this.Port); this.ClientConnection.NoDelay = true; lock (StateSyncObject) Writer = new System.IO.BinaryWriter(this.ClientConnection.GetStream()); //Thread.Sleep(3000); SendPacket(new PacketHeader(0, PayloadType.ClientConnection), new ClientConnectionPayload(ClientConnectionPayload.CurrentVersionMajor, ClientConnectionPayload.CurrentVersionMinor)); int read = 1; while (read > 0) { ms.SetLength(4); ms.Position = 0; while (ms.Position < 4) { read = this.ClientConnection.GetStream().Read(ms.GetBuffer(), (int)ms.Position, (int)ms.Length - (int)ms.Position); ms.Position += read; if (read <= 0) { break; } } if (read <= 0) { break; } //ms.SetLength(read); ms.Position = 0; PacketHeader header = new PacketHeader(reader); ms.Position = 0; if (header.PayloadLength > 0) { ms.SetLength(header.PayloadLength); while (ms.Position < header.PayloadLength) { read = this.ClientConnection.GetStream().Read(ms.GetBuffer(), (int)ms.Position, (int)ms.Length - (int)ms.Position); ms.Position += read; if (read <= 0) { break; } } ms.Position = 0; if (read <= 0) { break; } } if (header.Type == PayloadType.ServerDisconnect) { break; } else { HandlePacket(header, reader); } ms.Position = 0; } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception in ListenThreadEntrypoint: " + ex.ToString()); } if (!this.IsConnected) { this.ConnectedEvent.Set(); } this.ClientConnection?.Close(); this.ClientConnection?.Dispose(); System.Diagnostics.Debug.WriteLine("Connection closed."); this.IsConnected = false; //this.ServerDisconnect?.Invo //EventContext.Send((state) => { this.ServerDisconnect?.Invoke(null, null); }, null); lock (VMSyncObject) { VMState = null; } this.ServerDisconnect?.Invoke(this, new EventArgs()); this.ShutdownEvent.Set(); ms.Dispose(); reader.Dispose(); }
public static HeightData LoadHeightmapFromImageFile(string path) { Config config = Main.Get().GetConfig(); HeightData heights; string ext = path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')).ToLower(); if (ext == ".shd") { // byte-by-byte binary reading System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)); // read first eight bytes with map dimensions int width = reader.ReadInt32(); int height = reader.ReadInt32(); heights = new HeightData((UInt16)width, (UInt16)height); // read the double bytes containing the height data for (int i = 0; i < width * height; i++) { heights[i] = reader.ReadInt16(); } reader.Close(); reader.Dispose(); } else { // read the bitmap file System.Drawing.Bitmap bitmap; try { bitmap = new System.Drawing.Bitmap(path); } catch (ArgumentException) { return(null); } System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat); heights = new HeightData((UInt16)bitmap.Width, (UInt16)bitmap.Height); // prepare memory space for the color data byte[] bytes = new byte[data.Stride * bitmap.Height]; int pixelSize = data.Stride / data.Width; // get a pointer to the to first line (=first pixel) IntPtr ptr = data.Scan0; // create a byte copy of the heightmap data System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, data.Stride * bitmap.Height); // create the color data for (int i = 0; i < bytes.Length; i += pixelSize) { heights[i / pixelSize] = (short)((short)bytes[i] * 128); } bitmap.UnlockBits(data); bitmap.Dispose(); } HeightData heights2 = Main.GetResizedHeightData(heights, Math.Min(heights.Width, (int)config.mapDetailLevel), Math.Min(heights.Height, (int)config.mapDetailLevel)); return(heights2); }
public override void PrepareProcessing() { _reader?.Dispose(); try { _reader = new System.IO.BinaryReader(System.IO.File.OpenRead(_attrFilePath.TypedGet())); } catch (Exception ex) { Parent.Context.Notify(new GraphNotification(GraphNotification.NotificationType.Error, ex.ToString())); throw; } if (_reader != null) { _reader.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); _portOut.PrepareProcessing(); _portTrigger.PrepareProcessing(); _buffer = new TimeLocatedBuffer1D <double>(_portOut.Buffer.Capacity, _portOut.Samplerate); _endOfStream = false; if (_portTrigger.Connection == null) { _startTime = new TimeStamp(0); } } else { throw new Exception("File node: did not specify input"); } _lastStatePosition = 0; _sampleSize = _dataTypeSizes[_attrDataType.TypedGet()]; _sampleGetterFunc = () => { throw new System.IO.EndOfStreamException(); }; switch (_attrDataType.TypedGet()) { case DataType.Float32: _sampleGetterFunc = () => _reader.ReadSingle(); break; case DataType.Float64: _sampleGetterFunc = () => _reader.ReadDouble(); break; case DataType.Int16: _sampleGetterFunc = () => _reader.ReadInt16(); break; case DataType.Int32: _sampleGetterFunc = () => _reader.ReadInt32(); break; case DataType.Int64: _sampleGetterFunc = () => _reader.ReadInt64(); break; default: throw new NotImplementedException(); } }
public static HeightData LoadHeightmapFromImageFile(string path){ Config config = Main.Get().GetConfig(); HeightData heights; string ext = path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')).ToLower(); if (ext == ".shd") { // byte-by-byte binary reading System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read)); // read first eight bytes with map dimensions int width = reader.ReadInt32(); int height = reader.ReadInt32(); heights = new HeightData((UInt16) width,(UInt16) height); // read the double bytes containing the height data for (int i = 0; i < width * height; i++) { heights[i] = reader.ReadInt16(); } reader.Close(); reader.Dispose(); } else { // read the bitmap file System.Drawing.Bitmap bitmap; try { bitmap = new System.Drawing.Bitmap(path); } catch(ArgumentException){ return null; } System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); System.Drawing.Imaging.BitmapData data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat); heights = new HeightData((UInt16) bitmap.Width, (UInt16)bitmap.Height); // prepare memory space for the color data byte[] bytes = new byte[data.Stride * bitmap.Height]; int pixelSize = data.Stride / data.Width; // get a pointer to the to first line (=first pixel) IntPtr ptr = data.Scan0; // create a byte copy of the heightmap data System.Runtime.InteropServices.Marshal.Copy(ptr, bytes, 0, data.Stride * bitmap.Height); // create the color data for (int i = 0; i < bytes.Length; i += pixelSize) { heights[i / pixelSize] = (short)((short)bytes[i] * 128); } bitmap.UnlockBits(data); bitmap.Dispose(); } HeightData heights2 = Main.GetResizedHeightData(heights, Math.Min(heights.Width, (int)config.mapDetailLevel), Math.Min(heights.Height, (int)config.mapDetailLevel)); return heights2; }
/// <summary> /// Closes the underlying stream if was not set to leave open /// </summary> public void Close() { m_Reader.Dispose(); }
public void Load(AsyncCallback callback) { Func <bool> ac = () => { string path; #if DEBUG path = "settings.dat"; #else path = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Clocks"); path = System.IO.Path.Combine(path, "settings.dat"); #endif if (System.IO.File.Exists(path)) { System.IO.BinaryReader br = null; System.IO.FileStream fs = null; bool needDispose = true; try { fs = new System.IO.FileStream( path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); br = new System.IO.BinaryReader(fs); cfA = br.ReadByte(); cfR = br.ReadByte(); cfG = br.ReadByte(); cfB = br.ReadByte(); fgA = br.ReadByte(); fgR = br.ReadByte(); fgG = br.ReadByte(); fgB = br.ReadByte(); autoload = br.ReadBoolean(); showSeconds = br.ReadBoolean(); x = br.ReadDouble(); y = br.ReadDouble(); topMost = br.ReadBoolean(); } catch (System.IO.EndOfStreamException ex) { #if DEBUG // System.Windows.MessageBox.Show("1 path " + path + "\n" + ex.Message); #endif //освобождаем поток, чтоб удалить файл if (br != null) { br.Dispose(); } needDispose = false; try { System.IO.File.Delete(path); } catch (UnauthorizedAccessException) { } return(false); } catch (Exception ex) { #if DEBUG // System.Windows.MessageBox.Show("2 path " + path + "\n" +ex.Message); #endif return(false); } finally { if (needDispose) { if (br != null) { br.Dispose(); } } } } else { fgA = 255; fgR = 95; fgG = 158; fgB = 160; cfA = 255; cfR = 173; cfG = 216; cfB = 230; } return(true); }; ac.BeginInvoke(callback, null); }