public Boolean fromFile(String path) { FileStream fs = new FileStream(path, FileMode.Open); BinaryReader reader = new BinaryReader(fs); try { String h = reader.ReadString(); float v = BitConverter.ToSingle(reader.ReadBytes(sizeof(float)), 0); drawFloorModel = reader.ReadBoolean(); showAlwaysFloorMap = reader.ReadBoolean(); lockMapSize = reader.ReadBoolean(); mapXsize = reader.ReadInt32(); mapYsize = reader.ReadInt32(); //edgeXのxはmapX-1 //yはmapYsize return true; } catch (EndOfStreamException eex) { //握りつぶす return false; } finally { reader.Close(); } }
public static PEType GetPEType(string path) { if (string.IsNullOrEmpty(path)) return PEType.Unknown; var br = new BinaryReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite )); br.BaseStream.Seek(0x3C, SeekOrigin.Begin); br.BaseStream.Seek(br.ReadInt32() + 4, SeekOrigin.Begin); ushort machine = br.ReadUInt16(); br.Close(); if (machine == 0x014C) return PEType.X32; if (machine == 0x8664) return PEType.X64; return PEType.Unknown; }
private static string DeCrypting() { var res = string.Empty; var file = new FileStream(Controller.GetPath(), FileMode.Open, FileAccess.Read, FileShare.None, 32, FileOptions.SequentialScan); var reader = new BinaryReader(file); var writer = new BinaryWriter(new FileStream(Processor.GetNewName(Controller.GetPath()), FileMode.Create, FileAccess.Write, FileShare.None, 32, FileOptions.WriteThrough)); try { var pos = 0; while (pos < file.Length) { var c = reader.ReadUInt16(); //var pow = Processor.fast_exp(c, Controller.GetKc(), Controller.GetR()); var pow = Processor.Pows(c, Controller.GetKc(), Controller.GetR()); if (pos < 256) res += pow + " "; writer.Write((byte)(pow)); pos += 2; } } finally { writer.Close(); reader.Close(); } return "Decoding Complete!\n" + res; }
public static MacroBook[] Load(Character C) { string BookNameFile = C.GetUserFileName("mcr.ttl"); if (!File.Exists(BookNameFile)) return null; BinaryReader BR = new BinaryReader(new FileStream(BookNameFile, FileMode.Open, FileAccess.Read), Encoding.ASCII); int BookCount = 1; if ((BR.BaseStream.Length - 0x18) % 16 != 0 || BR.ReadUInt32() != 1) { BR.Close(); return null; } else { BookCount = (int) ((BR.BaseStream.Length - 0x18) / 16); } BR.BaseStream.Seek(0x18, SeekOrigin.Begin); List<MacroBook> Books = new List<MacroBook>(); for (int i = 0; i < BookCount; ++i) { MacroBook MB = new MacroBook(BookNameFile, i, new string(BR.ReadChars(16)).TrimEnd('\0')); for (int j = 0; j < 10; ++j) MB.Folders.Add(MacroSet.Load(C.GetUserFileName(string.Format("mcr{0:#####}.dat", 10 * i + j)), string.Format("Macro Set {0}", j + 1))); Books.Add(MB); } BR.Close(); return Books.ToArray(); }
static uint HEADER = 0x50414d57; // "WMAP" #endregion Fields #region Methods public static sFolder Unpack(string fileIn, string name) { name = Path.GetFileNameWithoutExtension(name); BinaryReader br = new BinaryReader(File.OpenRead(fileIn)); sFolder unpack = new sFolder(); unpack.files = new List<sFile>(); if (br.ReadUInt32() != HEADER) { br.Close(); br = null; throw new FormatException("Invalid header!"); } uint num_files = br.ReadUInt32(); br.ReadUInt32(); // Unknown 1 br.ReadUInt32(); // Unknown 2 for (int i = 0; i < num_files; i++) { sFile cfile = new sFile(); cfile.name = name + '_' + i.ToString() + ".bin"; cfile.offset = br.ReadUInt32(); cfile.size = br.ReadUInt32(); cfile.path = fileIn; unpack.files.Add(cfile); } br.Close(); br = null; return unpack; }
private void importBtn_Click(object sender, EventArgs e) { OpenFileDialog ifModel = new OpenFileDialog(); ifModel.Title = rm.GetString("selectModel"); ifModel.Filter = rm.GetString("importModelFile"); if (ifModel.ShowDialog() == DialogResult.OK) { System.IO.BinaryReader modelStream = new System.IO.BinaryReader(File.OpenRead(ifModel.FileName)); string importModel = ifModel.FileName; long importnsbmdSize = new System.IO.FileInfo(ifModel.FileName).Length; int header; header = (int)modelStream.ReadUInt32(); if (header == 809782594) { modelStream.Close(); File.Copy(ifModel.FileName, bldPath + "\\" + listBox1.SelectedIndex.ToString("D4"), true); } else { MessageBox.Show(rm.GetString("invalidFile"), null, MessageBoxButtons.OK, MessageBoxIcon.Stop); modelStream.Close(); } } }
public static ImageFileType ExamineImage(string file) { byte[] magic; using (var sr = new BinaryReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))) { if (sr.BaseStream.Length < 3) { sr.Close(); return ImageFileType.Invalid; } magic = sr.ReadBytes(3); sr.Close(); } if (magic[0] == 0xFF && magic[1] == 0xD8 && magic[2] == 0xFF) return ImageFileType.Jpeg; if (magic[0] == 0x89 && magic[1] == 0x50 && magic[2] == 0x4E) return ImageFileType.Png; return ImageFileType.Invalid; }
public static ExtractedM2 Process(string basePath, MapId mapId, string path) { basePath = Path.Combine(basePath, mapId.ToString()); var filePath = Path.Combine(basePath, path); filePath = Path.ChangeExtension(filePath, ".m2x"); if (!File.Exists(filePath)) { throw new FileNotFoundException("Extracted M2 file not found: {0}", filePath); } var m2 = new ExtractedM2(); using(var file = File.OpenRead(filePath)) using(var br = new BinaryReader(file)) { var type = br.ReadString(); if (type != fileType) { br.Close(); throw new InvalidDataException(string.Format("M2x file in invalid format: {0}", filePath)); } m2.Extents = br.ReadBoundingBox(); m2.BoundingVertices = br.ReadVector3List(); m2.BoundingTriangles = br.ReadIndex3List(); br.Close(); } return m2; }
public bool LoadMinstFiles() { //clear Image Pattern List if (m_pImagePatterns != null) { m_pImagePatterns.Clear(); } //close files if opened if (_bImageFileOpen) { load_ImageFile_stream.Close(); _bImageFileOpen = false; } if (_bLabelFileOpen) { load_LabelFile_stream.Close(); _bLabelFileOpen = false; } //load Mnist Images files. if (!MnistImageFileHeader()) { MessageBox.Show("Can not open Image file"); _MnistImageFileName = null; _bImageFileOpen = false; _bDatabase = false; return(false); } if (!MnistLabelFileHeader()) { MessageBox.Show("Can not open label file"); _MnistLabelFileName = null; _bLabelFileOpen = false; _bDatabase = false; return(false); } //check the value if image file and label file have been opened successfully if (_LabelFileBegin.nItems != _ImageFileBegin.nItems) { MessageBox.Show("Item numbers are different"); CloseMinstFiles(); _bDatabase = false; return(false); } m_pImagePatterns = new List <ImagePattern>(_ImageFileBegin.nItems); _iRandomizedPatternSequence = new int[_ImageFileBegin.nItems]; for (int i = 0; i < _ImageFileBegin.nItems; i++) { byte m_nlabel; byte[] m_pPatternArray = new byte[MyDefinations.g_cImageSize * MyDefinations.g_cImageSize]; ImagePattern m_ImagePattern = new ImagePattern(); GetNextPattern(m_pPatternArray, out m_nlabel, i, true); m_ImagePattern.pPattern = m_pPatternArray; m_ImagePattern.nLabel = m_nlabel; m_pImagePatterns.Add(m_ImagePattern); } _bDatabase = true; CloseMinstFiles(); return(true); }
public void BinaryReader_CloseTests() { // Closing multiple times should not throw an exception using (Stream memStream = CreateStream()) using (BinaryReader binaryReader = new BinaryReader(memStream)) { binaryReader.Close(); binaryReader.Close(); binaryReader.Close(); } }
private void importBtn_Click(object sender, EventArgs e) // Import model { OpenFileDialog ifModel = new OpenFileDialog(); ifModel.Title = rm.GetString("selectModel"); ifModel.Filter = rm.GetString("importModelFile"); if (ifModel.ShowDialog() == DialogResult.OK) { System.IO.BinaryReader modelStream = new System.IO.BinaryReader(File.OpenRead(ifModel.FileName)); string importModel = ifModel.FileName; long importnsbmdSize = new System.IO.FileInfo(ifModel.FileName).Length; int header; header = (int)modelStream.ReadUInt32(); if (header == 809782594) { modelStream.BaseStream.Position = 0x18; header = (int)modelStream.ReadUInt32(); if (header == 810304589) { MessageBox.Show(rm.GetString("embeddedTextures")); System.IO.BinaryWriter write = new System.IO.BinaryWriter(File.Create(bldPath + "\\" + "model" + "\\" + listBox1.SelectedIndex.ToString("D4"))); modelStream.BaseStream.Position = 0x14; importnsbmdSize = (int)(modelStream.ReadUInt32() - 0x4); write.Write((int)809782594); write.Write((int)0x02FEFF); write.Write((int)importnsbmdSize); write.Write((int)0x010010); write.Write((int)0x14); for (int i = 0; i < importnsbmdSize - 0x14; i++) { write.Write(modelStream.ReadByte()); // Reads import file bytes and writes them to the main file } modelStream.Close(); write.Close(); } else { modelStream.Close(); File.Copy(ifModel.FileName, bldPath + "\\" + "model" + "\\" + listBox1.SelectedIndex.ToString("D4"), true); } int index = listBox1.SelectedIndex; button1_Click(null, null); comboBox1_SelectedIndexChanged(null, null); listBox1.SelectedIndex = index; } else { MessageBox.Show(rm.GetString("invalidFile"), null, MessageBoxButtons.OK, MessageBoxIcon.Stop); modelStream.Close(); } } }
public static ClipboardBuffer Load(string filename) { string ext = Path.GetExtension(filename); if (string.Equals(ext, ".jpg", StringComparison.InvariantCultureIgnoreCase) || string.Equals(ext, ".png", StringComparison.InvariantCultureIgnoreCase) || string.Equals(ext, ".bmp", StringComparison.InvariantCultureIgnoreCase)) return LoadFromImage(filename); using (var stream = new FileStream(filename, FileMode.Open)) { using (var b = new BinaryReader(stream)) { string name = b.ReadString(); int version = b.ReadInt32(); uint tVersion = (uint)version; // check all the old versions if (version < 78) { return Load5(b, name, tVersion, version); } else if (version == 4) { b.Close(); stream.Close(); return Load4(filename); } else if (version == 3) { b.Close(); stream.Close(); return Load3(filename); } else if (version == 2) { b.Close(); stream.Close(); return Load2(filename); } else if (version < 2) { b.Close(); stream.Close(); return LoadOld(filename); } // not and old version, use new version return LoadV2(b, name, tVersion, version); } } }
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 SPKImage(Palette p, Stream s, int width, int height) { //int transparent=254; idx = new byte[width*height]; for(int i=0;i<idx.Length;i++) idx[i]=254; long pix=0; BinaryReader data = new BinaryReader(s); try { while(data.BaseStream.Position < data.BaseStream.Length) { int cas = data.ReadUInt16(); switch(cas) { case 0xFFFF: { long val = data.ReadUInt16()*2; pix+=val; break; } case 0xFFFE: { long val = data.ReadUInt16()*2; while((val--)>0) { idx[pix++] = data.ReadByte(); } break; } case 0xFFFD: { image = Bmp.MakeBitmap8(width,height,idx,p.Colors); Palette=p; data.Close(); return; } } } } catch{} image = Bmp.MakeBitmap8(width,height,idx,p.Colors); Palette=p; data.Close(); }
////////////////////////////////////////////////////////////////////////////////////////////////////// // Leer fichero ANA ////////////////////////////////////////////////////////////////////////////////////////////////////// private void buttonANA_Click(object sender, EventArgs e) { uint anafile_size; uint subfiles_count; if (openFileDialog.ShowDialog() == DialogResult.OK) { Files.Clear(); // Borrar archivos anteriores listBox.Items.Clear(); // Borrar lista anterior filename = openFileDialog.FileName; labelFilename.Text = Path.GetFileName(filename); BinaryReader file = new BinaryReader(File.Open(filename, FileMode.Open)); if (file.ReadUInt32() != 0x414E4140) // 40 41 4E 41 { MessageBox.Show("Incorrect header. Correct file?"); file.Close(); return; } file.ReadUInt32(); // Read (non)padding anafile_size = file.ReadUInt32(); // Read ANA size file.ReadUInt32(); // Read (non)padding subfiles_count = file.ReadUInt32(); file.ReadUInt32(); file.ReadUInt32(); file.ReadUInt32(); // Read padding for (uint i = 0; i < subfiles_count; i++) { SubFile temp = new SubFile(); temp.offset = file.ReadUInt32(); temp.size = file.ReadUInt32(); temp.filename = new String(file.ReadChars(8)).Trim('\0'); Files.Add(temp); listBox.Items.Add(temp.filename); } listBox.Sorted = false; // Meter el contenido de cada fichero en un buffer, para no liar el reemplazo demasiado for (int i = 0; i < Files.Count; i++) { file.BaseStream.Seek(Files[i].offset, SeekOrigin.Begin); Files[i].buffer = file.ReadBytes((int)Files[i].size); } // experimental // copiar fragmento ANT a un buffer para luego file.BaseStream.Seek(Files[Files.Count - 1].offset + Files[Files.Count - 1].size, SeekOrigin.Begin); ant_section = file.ReadBytes((int)file.BaseStream.Length - (int)file.BaseStream.Position); // experimental file_type = "ana"; file.Close(); } }
public static bool isImagePaletted(string name) { System.IO.FileStream str1 = new System.IO.FileStream(name, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite); BinaryReader inf = new System.IO.BinaryReader(str1); if (inf.BaseStream.Length == 0) { inf.Close(); return false; } int f = inf.ReadInt32(); inf.Close(); return f == 0; }
public static void Decrypt(string file_input, string file_output, string key1) { FileStream input; BinaryReader br; FileStream output; BinaryWriter bw; byte[] block; key = new Key(key1); Utils.key.makeKey(); Utils.key.reverseKey(); try { input = new FileStream(file_input, FileMode.Open, FileAccess.Read); br = new BinaryReader(input); output = new FileStream(file_output, FileMode.Create, FileAccess.Write); bw = new BinaryWriter(output); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } //// try { while ((block = br.ReadBytes(8)).Length > 0) { BitArray encrypted_message = Utils.makeMessage(napraw(block)); bw.Write((encrypted_message.ToByteArray())); } } catch (Exception ex) { MessageBox.Show(ex.Message); input.Close(); output.Close(); br.Close(); bw.Close(); } finally { input.Close(); output.Close(); br.Close(); bw.Close(); } }
/* Achtung! Hier fehlt noch jegliches Error-Handling Es wird nicht einmal geprüft ob die Datei mit VADB anfängt! */ public VDB_Table[] ImportTables(string filename) { BinaryReader reader = new BinaryReader(File.Open(filename, FileMode.Open)); string formatID = reader.ReadString(); int formatVersion = reader.ReadInt32(); int tableCount = reader.ReadInt32(); VDB_Table[] tables = new VDB_Table[tableCount]; for (int i = 0; i < tableCount; i++) { string tableName = reader.ReadString(); int columnCount = reader.ReadInt32(); string[] columns = new string[columnCount]; for (int j = 0; j < columnCount; j++) { columns[j] = reader.ReadString(); } int rowCount = reader.ReadInt32(); tables[i] = new VDB_Table(tableName, rowCount, columns); } string valueArea = reader.ReadString(); string[] values = valueArea.Split(VDB_DatabaseExporter.valuesSeperator); for (int i = 0; i < values.Length - 1; i++) { string[] posval = values[i].Split(VDB_DatabaseExporter.positionValueSeperator); string[] pos = posval[0].Split(VDB_DatabaseExporter.positionSeperator); int table = Int32.Parse(pos[0]); int row = Int32.Parse(pos[1]); int column = Int32.Parse(pos[2]); tables[table].GetRowAt(row).values[column] = VDB_Value.FromBase64(posval[1]); } reader.Close(); return tables; }
/// 通过给定的文件流,判断文件的编码类型 /// <param name="fs">文件流</param> /// <returns>文件的编码类型</returns> public static System.Text.Encoding GetType(System.IO.FileStream fs) { byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 }; byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 }; byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM System.Text.Encoding reVal = System.Text.Encoding.Default; System.IO.BinaryReader r = new System.IO.BinaryReader(fs, System.Text.Encoding.Default); int i; int.TryParse(fs.Length.ToString(), out i); byte[] ss = r.ReadBytes(i); if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF)) { reVal = System.Text.Encoding.UTF8; } else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00) { reVal = System.Text.Encoding.BigEndianUnicode; } else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41) { reVal = System.Text.Encoding.Unicode; } r.Close(); return(reVal); }
private void LoadFile(string filename) { BinaryReader reader = new BinaryReader(new FileStream(filename, FileMode.Open)); int appCount = reader.ReadInt32(); appInfos.Clear(); DataTable dt = new DataTable(); foreach (FieldInfo pInfo in typeof(AppInfo).GetFields()) { dt.Columns.Add(pInfo.Name, pInfo.FieldType); } for (int i = 0; i < appCount; ++i) { AppInfo appInfo = new AppInfo(); appInfo.read(reader); appInfos.Add(appInfo); object[] fields = new object[typeof(AppInfo).GetFields().Length]; int j = 0; foreach (FieldInfo pInfo in typeof(AppInfo).GetFields()) { fields[j++] = pInfo.GetValue(appInfo); } dt.Rows.Add(fields); } dataGridView1.DataSource = appInfos; reader.Close(); }
private void button1_Click(object sender, EventArgs e) { try { OpenFileDialog dialog = new OpenFileDialog(); dialog.ValidateNames = true; dialog.CheckFileExists = true; dialog.CheckPathExists = true; dialog.Multiselect = false; if (dialog.ShowDialog() == DialogResult.OK) { long fileSize = (new FileInfo(dialog.FileName)).Length; if (fileSize > MaxAllowedSize) throw new Exception("File is too large"); using (FileStream fs = new FileStream(dialog.FileName, FileMode.Open)) { BinaryReader br = new BinaryReader(fs); request_content = br.ReadBytes((int)fileSize); br.Close(); fs.Close(); } label2.Text = dialog.SafeFileName; textBox2.Text = System.Text.Encoding.Default.GetString(request_content); textBox2.Modified = false; } } catch (Exception err) { MessageBox.Show(err.Message, "Exception"); } }
public ScannerProps(byte[] data) { BinaryReader br = new System.IO.BinaryReader(new MemoryStream(data)); WorkMode = (WorkMode)br.ReadInt16(); DpiX0 = br.ReadInt16(); DpiY0 = br.ReadInt16(); DpiX1 = br.ReadInt16(); DpiY1 = br.ReadInt16(); DoubleSheet = (DoubleSheet)br.ReadInt16(); Marker = (Marker)br.ReadInt16(); DoubleSheetLevelL = br.ReadInt16(); WhiteCoeff = (WhiteCoeff)br.ReadInt16(); BinaryThreshold0 = br.ReadInt16(); BinaryThreshold1 = br.ReadInt16(); MinSheetLength = br.ReadInt16(); MaxSheetLength = br.ReadInt16(); DoubleSheetLevelR = br.ReadInt16(); TuningMode = (TuningMode)br.ReadInt16(); MarkerWork = br.ReadInt16(); DirtDetection = (DirtDetection)br.ReadInt16(); OfflineMode = br.ReadInt16(); Lamps = (Lamps)br.ReadInt16(); reserv = new short[21]; for (int i = 0; i < reserv.Length; i++) { reserv[i] = br.ReadInt16(); } br.Close(); }
/// <summary> /// Loads file into byte array. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns>Byte[].</returns> public static Byte[] LoadFromFile(this string fileName) { Byte[] buffer = null; try { // Open file for reading var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach file stream to binary reader var binaryReader = new System.IO.BinaryReader(fileStream); // get total byte length of the file var totalBytes = new System.IO.FileInfo(fileName).Length; // read entire file into buffer buffer = binaryReader.ReadBytes((Int32)totalBytes); // close file reader fileStream.Close(); fileStream.Dispose(); binaryReader.Close(); } catch (Exception exception) { var a = exception; } return(buffer); }
static void Main(string[] args) { // Create digital signature algortihm object // This will generate private/public key pair RSACryptoServiceProvider signer = new RSACryptoServiceProvider(); // array to hold signature - will be shared byte[] signature = null; // string to hold public key - will be shared string publicKey = null; using(FileStream file = new FileStream(@"info.txt", FileMode.Open, FileAccess.Read)) { // read file to be used to create signature into a byte array BinaryReader reader = new BinaryReader(file); byte[] data = reader.ReadBytes((int)file.Length); // create signature by signing data - generates a digital signature by first // generating the hash the data and then generate a signature based on the // hash and the private key // file, signature and public key are then shared with the recipient signature = signer.SignData(data,new SHA1CryptoServiceProvider()); // export public key publicKey = signer.ToXmlString(false); reader.Close(); file.Close(); } // Create digital signature algortihm object // which will use the public key exported by the signer RSACryptoServiceProvider verifier = new RSACryptoServiceProvider(); verifier.FromXmlString(publicKey); using (FileStream file2 = new FileStream(@"info.txt", FileMode.Open, FileAccess.Read)) { // read file to be used to verify the signature into a byte array BinaryReader reader2 = new BinaryReader(file2); byte[] data2 = reader2.ReadBytes((int)file2.Length); // verify the signature based on the contents of the file // verification will only succeed if the signature was generated from this // file using the correct private key, thus confirming the identity of the // signer if (verifier.VerifyData(data2, new SHA1CryptoServiceProvider(), signature)) { Console.WriteLine("Verified"); } else { Console.WriteLine("NOT verified"); } reader2.Close(); file2.Close(); } }
/// <summary> /// 检测文件真实 扩展名 /// </summary> /// <param name="path"></param> /// <returns></returns> public static FileExtension CheckTrueFileName(string path) { System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs); string bx = " "; byte buffer; try { buffer = r.ReadByte(); bx = buffer.ToString(); buffer = r.ReadByte(); bx += buffer.ToString(); } catch (Exception exc) { Console.WriteLine(exc.Message); } r.Close(); fs.Close(); int type = 0; int.TryParse(bx, out type); return((FileExtension)type); }
private bool FileCopy(string srcfilename, string destfilename) { if (System.IO.File.Exists(srcfilename) == false) { return(false); } System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite); System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create, FileAccess.ReadWrite, FileShare.Delete); System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1); System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2); while (true) { byte[] buf = new byte[10240]; int sz = f1.Read(buf, 0, 10240); if (sz <= 0) { break; } f2.Write(buf, 0, sz); if (sz < 10240) { break; } } f1.Close(); f2.Close(); return(true); }
public static Byte[] ReadFile(string copyFrom, string trueProcessName) { Byte[] filecontents = null; int retry = 1; while (filecontents == null & retry <= 5) { try { System.IO.FileStream Strm = new System.IO.FileStream(copyFrom, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm); filecontents = reader.ReadBytes(int.Parse(Strm.Length.ToString())); reader.Close(); Strm.Close(); Utils.WriteToLog(LogSeverity.Info, trueProcessName, String.Format("Success reading file '{0}' on attempt {1}", copyFrom, retry)); } catch (Exception e) { Utils.WriteToLog(LogSeverity.Error, processName, String.Format("Error reading file '{0}' on attempt {1}, error: {2}", copyFrom, retry, e.Message)); retry++; Thread.Sleep(1000 * 60); // Wait 60 secs } } return(filecontents); }
public static byte[] FileToByteArray(string _FileName) { byte[] _Buffer = null; try { // Open file for reading FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); //attach filestream to binary reader BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); //get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_FileName).Length; //read entire file into buffer _Buffer = _BinaryReader.ReadBytes((int)_TotalBytes); //close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception ex) { throw ex; } return(_Buffer); }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { listBox1.Items.Clear(); AB.Extract(bldPath + "\\" + comboBox1.SelectedIndex.ToString("D4"), bldPath); for (int i = 0; i < Directory.GetFiles(bldPath + "\\" + "header").Length; i++) { string bldName = ""; System.IO.BinaryReader readID = new System.IO.BinaryReader(File.OpenRead(bldPath + "\\" + "header" + "\\" + i.ToString("D4"))); System.IO.BinaryReader read = new System.IO.BinaryReader(File.OpenRead(bldPath + "\\" + "model" + "\\" + i.ToString("D4"))); read.BaseStream.Position = 0x14; if (read.ReadUInt32() == 0x304C444D) { read.BaseStream.Position = 0x34; } else { read.BaseStream.Position = 0x38; } for (int nameLength = 0; nameLength < 16; nameLength++) { int currentByte = read.ReadByte(); byte[] mapBytes = new Byte[] { Convert.ToByte(currentByte) }; // Reads map name if (currentByte != 0) { bldName = bldName + Encoding.UTF8.GetString(mapBytes); } } listBox1.Items.Add(i.ToString("D2") + ": " + bldName + " (" + readID.ReadInt16() + ")"); read.Close(); readID.Close(); } listBox1.SelectedIndex = 0; }
public static byte[] Decrypt(string filename, string key, string salt) { System.IO.BinaryReader filein = new System.IO.BinaryReader(new System.IO.StreamReader(filename).BaseStream); byte[] data = filein.ReadBytes((int)filein.BaseStream.Length); filein.Close(); try { return(Decrypt(data, key, salt)); } catch (Exception e) { string err; try { err = e.Message + Environment.NewLine + e.InnerException.Message; } catch { err = e.Message; } Globals.l2net_home.Add_PopUpError("failed to decrypt '" + filename + "' file data" + Environment.NewLine + err); throw e; } }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { var fileStream = new FileStream(bldPath + "\\" + "model" + "\\" + listBox1.SelectedIndex.ToString("D4"), FileMode.Open); file_2 = bldPath + "\\" + "model" + "\\" + listBox1.SelectedIndex.ToString("D4"); _nsbmd = NsbmdLoader.LoadNsbmd(fileStream); if (!checkBox1.Checked) { _nsbmd.materials = LibNDSFormats.NSBTX.NsbtxLoader.LoadNsbtx(new MemoryStream(File.ReadAllBytes(Form1.workingFolder + @"data\a\1\7\bldtilesets" + "\\" + comboBox1.SelectedIndex.ToString("D4"))), out _nsbmd.Textures, out _nsbmd.Palettes); } else { _nsbmd.materials = LibNDSFormats.NSBTX.NsbtxLoader.LoadNsbtx(new MemoryStream(File.ReadAllBytes(Form1.workingFolder + @"data\a\1\7\bld2tilesets" + "\\" + comboBox1.SelectedIndex.ToString("D4"))), out _nsbmd.Textures, out _nsbmd.Palettes); } try { _nsbmd.MatchTextures(); } catch { } RenderBuilding(null, null); fileStream.Close(); System.IO.BinaryReader readHeader = new System.IO.BinaryReader(File.OpenRead(bldPath + "\\" + "header" + "\\" + listBox1.SelectedIndex.ToString("D4"))); numericUpDown1.Value = readHeader.ReadUInt16(); // ID readHeader.BaseStream.Position += 2; numericUpDown2.Value = readHeader.ReadUInt16(); // Door ID numericUpDown3.Value = readHeader.ReadInt16(); // X numericUpDown4.Value = readHeader.ReadInt16(); // Y numericUpDown5.Value = readHeader.ReadInt16(); // Z readHeader.Close(); }
public static void SaveStreamToFile(Stream FromStream, string TargetFile) { // FromStream=the stream we wanna save to a file //TargetFile = name&path of file to be created to save to //i.e"c:\mysong.mp3" try { //Creat a file to save to Stream ToStream = File.Create(TargetFile); //use the binary reader & writer because //they can work with all formats //i.e images, text files ,avi,mp3.. BinaryReader br = new BinaryReader(FromStream); BinaryWriter bw = new BinaryWriter(ToStream); //copy data from the FromStream to the outStream //convert from long to int bw.Write(br.ReadBytes((int)FromStream.Length)); //save bw.Flush(); //clean up bw.Close(); br.Close(); } //use Exception e as it can handle any exception catch (Exception e) { //code if u like } }
/// <summary> /// 是否允许 /// </summary> public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx) { int fileLen = oFile.ContentLength; byte[] imgArray = new byte[fileLen]; oFile.InputStream.Read(imgArray, 0, fileLen); MemoryStream ms = new MemoryStream(imgArray); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); ms.Close(); foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) return true; } return false; }
/// <summary> /// 是否为真实的图片文件 /// </summary> /// <param name="hpfile"></param> /// <returns></returns> private bool IsRealImage(HttpPostedFile hpfile) { bool ret = false; System.IO.BinaryReader r = new System.IO.BinaryReader(hpfile.InputStream); string fileclass = ""; byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { return(false); } r.Close(); /*文件扩展名说明 * 7173 gif * 255216 jpg * 13780 png * 6677 bmp */ String[] fileType = { "255216", "7173", "6677", "13780" }; ret = Array.IndexOf(fileType, fileclass) >= 0; return(ret); }
/// <summary> ///图片检测类 是否允许 /// </summary> public static bool IsAllowedExtension(HttpPostedFile oFile, FileExtension[] fileEx) { int fileLen = oFile.ContentLength; var imgArray = new byte[fileLen]; oFile.InputStream.Read(imgArray, 0, fileLen); var ms = new MemoryStream(imgArray); var br = new System.IO.BinaryReader(ms); string fileclass = ""; try { byte buffer = br.ReadByte(); fileclass = buffer.ToString(CultureInfo.InvariantCulture); buffer = br.ReadByte(); fileclass += buffer.ToString(CultureInfo.InvariantCulture); } catch { } br.Close(); ms.Close(); foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) { return(true); } } return(false); }
//真正判断文件类型的关键函数 public static bool IsAllowedExtension(FileUpload hifile) { string path = hifile.PostedFile.FileName; //只能访问服务器的文件系统 //本地测试是 ie hifile.PostedFile.FileName; 返回完整路径, chrome 中得到的是文件名 //path = @"e:\2015072709244673595997.jpg"; System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs); string fileclass = ""; //这里的位长要具体判断. byte buffer; try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); } catch { } r.Close(); fs.Close(); if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar { return(true); } else { return(false); } }
public byte[] FilenameToBytes(string filename) { byte[] data = null; // get the file information form the selected file FileInfo fInfo = new FileInfo(filename); // get the length of the file to see if it is possible // to upload it (with the standard 4 MB limit) long numBytes = fInfo.Length; double dLen = Convert.ToDouble(fInfo.Length / 1000000); // set up a file stream and binary reader for the // selected file FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fStream); // convert the file to a byte array data = br.ReadBytes((int)numBytes); br.Close(); fStream.Close(); fStream.Dispose(); return data; }
static public byte[] FileToByteArray(string _FileName) { byte[] _Buffer = null; try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_FileName).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); // close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception _Exception) { Console.WriteLine("Exception caught in process: {0}", _Exception.ToString()); } return(_Buffer); }
private void loadFromFile(string fileName) { if (!File.Exists(fileName)) { return; } FileStream fstream = File.OpenRead(fileName); BinaryReader reader = new BinaryReader(fstream); int cnt = reader.ReadInt32(); for (int i = 0; i < cnt; i++) { string symbol = reader.ReadString(); int stockCount = reader.ReadInt32(); int buyPrice = reader.ReadInt32(); PortfolioItem item = new PortfolioItem() { Symbol = symbol, Amount = stockCount, BuyPrice = buyPrice, }; list.Add(item); } reader.Close(); fstream.Close(); }
private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { if (listBox2.SelectedIndex == -1) { button4.Enabled = false; return; } button4.Enabled = true; System.IO.BinaryReader readEvent = new System.IO.BinaryReader(File.OpenRead(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); readEvent.BaseStream.Position = 0x8 + 0x14 * furnitureCount + 0x20 * listBox2.SelectedIndex; numericUpDown34.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown33.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown32.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown31.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown30.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown36.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown38.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown40.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown29.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown28.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown27.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown26.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown25.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown35.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown37.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); numericUpDown39.Value = readEvent.ReadByte() + (readEvent.ReadByte() << 8); readEvent.Close(); }
static ItemBounds() { m_Bounds = new Rectangle2D[TileData.ItemTable.Length]; if (File.Exists("Data/Binary/Bounds.bin")) { using (FileStream fs = new FileStream("Data/Binary/Bounds.bin", FileMode.Open, FileAccess.Read, FileShare.Read)) { BinaryReader bin = new BinaryReader(fs); int count = Math.Min(m_Bounds.Length, (int)(fs.Length / 8)); for (int i = 0; i < count; ++i) { int xMin = bin.ReadInt16(); int yMin = bin.ReadInt16(); int xMax = bin.ReadInt16(); int yMax = bin.ReadInt16(); m_Bounds[i].Set(xMin, yMin, (xMax - xMin) + 1, (yMax - yMin) + 1); } bin.Close(); } } else { Console.WriteLine("Warning: Data/Binary/Bounds.bin does not exist"); } }
private void button7_Click(object sender, EventArgs e) { System.IO.BinaryReader readEvent = new System.IO.BinaryReader(File.OpenRead(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); File.Create(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new").Close(); System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new")); for (int i = 0; i < (0xc + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * warpCount); i++) { writeEvent.Write(readEvent.ReadByte()); // Reads unmodified bytes and writes them to the main file } for (int i = 0; i < (0xc); i++) { writeEvent.Write((byte)0x0); // Writes new warp } for (int i = 0; i < (readEvent.BaseStream.Length - (0xc + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * warpCount)); i++) { writeEvent.Write(readEvent.ReadByte()); // Reads unmodified bytes and writes them to the main file } writeEvent.BaseStream.Position = 0x8 + furnitureCount * 0x14 + overworldCount * 0x20; writeEvent.Write(warpCount + 1); warpCount++; readEvent.Close(); writeEvent.Close(); File.Delete(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4")); File.Move(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new", eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4")); comboBox1_SelectedIndexChanged(null, null); }
public static byte[] GetByteArray(String strFileName) { System.IO.FileStream fs = null; System.IO.BinaryReader br; byte[] imgbyte = null; try { fs = new System.IO.FileStream(strFileName, System.IO.FileMode.Open); // initialise the binary reader from file streamobject br = new System.IO.BinaryReader(fs); // define the byte array of filelength imgbyte = new byte[fs.Length + 1]; // read the bytes from the binary reader imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length))); br.Close(); } catch (Exception ex) { } finally { } // add the image in bytearray // close the binary reader if (fs != null) { fs.Close(); } // close the file stream return(imgbyte); }
public static List <DbfFieldDescriptor> GetDbfSchema(string dbfFileName, Encoding encoding) { System.IO.Stream stream = new System.IO.FileStream(dbfFileName, System.IO.FileMode.Open); System.IO.BinaryReader reader = new System.IO.BinaryReader(stream); byte[] buffer = reader.ReadBytes(Marshal.SizeOf(typeof(DbfHeader))); DbfHeader header = IRI.Ket.IO.BinaryStream.ByteArrayToStructure <DbfHeader>(buffer); List <DbfFieldDescriptor> columns = new List <DbfFieldDescriptor>(); if ((header.LengthOfHeader - 33) % 32 != 0) { throw new NotImplementedException(); } int numberOfFields = (header.LengthOfHeader - 33) / 32; for (int i = 0; i < numberOfFields; i++) { buffer = reader.ReadBytes(Marshal.SizeOf(typeof(DbfFieldDescriptor))); columns.Add(DbfFieldDescriptor.Parse(buffer, encoding)); } reader.Close(); stream.Close(); return(columns); }
public static bool ReadFile(string FileName) { LCMeshReader.OpenedFile = FileName; LCMeshReader.pMesh = new tMeshContainer(); BinaryReader b = new BinaryReader( new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)); LCMeshReader.pMesh.HeaderInfo = new tHeaderInfo(); LCMeshReader.pMesh.HeaderInfo.Format = b.ReadBytes(4); LCMeshReader.pMesh.HeaderInfo.Version = b.ReadInt32(); LCMeshReader.pMesh.HeaderInfo.MeshDataSize = b.ReadInt32(); LCMeshReader.pMesh.HeaderInfo.MeshCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.VertexCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.JointCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.TextureMaps = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.NormalCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.ObjCount = b.ReadUInt32(); LCMeshReader.pMesh.HeaderInfo.UnknownCount = b.ReadUInt32(); LCMeshReader.pMesh.FileName = b.ReadBytes(b.ReadInt32()); LCMeshReader.pMesh.Scale = b.ReadSingle(); LCMeshReader.pMesh.Value1 = b.ReadUInt32(); LCMeshReader.pMesh.FilePath = FileName; bool flag = false; if (LCMeshReader.pMesh.HeaderInfo.Version == 16) { if (LCMeshReader.ReadV10(b, b.BaseStream.Position)) flag = true; } else if (LCMeshReader.pMesh.HeaderInfo.Version == 17 && LCMeshReader.ReadV11(b, b.BaseStream.Position)) flag = true; b.Close(); return flag; }
public static void Convert(string icofile) { System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream(icofile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)); NewHeader nh = new NewHeader(); nh.Read(br); ResDir[] rd = new ResDir[nh.ResCount]; for (int i = 0; i < nh.ResCount; i++) { rd[i].Read(br); } byte[] bits = new byte[0]; for (int i = 0; i < nh.ResCount; i++) { br.BaseStream.Seek(rd[i].Offset, System.IO.SeekOrigin.Begin); if (bits.Length < rd[i].BytesInRes) { bits = new byte[rd[i].BytesInRes]; } br.Read(bits, 0, rd[i].BytesInRes); int bitcount, width, height; System.Drawing.Bitmap bm = Decode(bits, 0, rd[i].BytesInRes, out width, out height, out bitcount); string fileName = string.Format("{0}-{1}x{2}-{3}bpp.png", System.IO.Path.GetFileNameWithoutExtension(icofile), width, height, bitcount); bm.Save(fileName); bm.Dispose(); Console.WriteLine(string.Format(" Saved {0}", fileName)); } br.Close(); }
public static bool IsAllowedExtension(MemoryStream ms, FileExtension[] fileEx) { System.IO.BinaryReader br = new System.IO.BinaryReader(ms); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); ms.Close(); foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) { return(true); } } return(false); }
public HttpResponseMessage DownLoadFile(string FileName, string fileType) { List<String> valores = new List<string>(); Byte[] bytes = null; if (FileName != null) { string filePath = Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), FileName)); FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); bytes = br.ReadBytes((Int32)fs.Length); br.Close(); fs.Close(); } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); System.IO.MemoryStream stream = new MemoryStream(bytes); result.Content = new StreamContent(stream); result.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = FileName }; return (result); }
//public ushort MaxAudioLevel; private static WaveProcessor WaveHeaderIN(char Digit) { String Path = HttpContext.Current.Server.MapPath(String.Format("~/Epayment/DigitVoice/{0}.WAV", Digit)); FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); try { WaveProcessor Header = new WaveProcessor {Length = (int) fs.Length - 8}; fs.Position = 22; Header.Channels = br.ReadInt16(); //1 fs.Position = 24; Header.SampleRate = br.ReadInt32(); //8000 fs.Position = 34; Header.BitsPerSample = br.ReadInt16(); //16 Header.DataLength = (int)fs.Length - 44; byte[] arrfile = new byte[fs.Length - 44]; fs.Position = 44; fs.Read(arrfile, 0, arrfile.Length); return Header; } finally { br.Close(); fs.Close(); } }
protected bool IsImageFile(HttpPostedFile httpPostedFile) { bool isImage = false; string fullPath = Server.MapPath("~/Profile Pic/" + FileUpload1.FileName); FileUpload1.SaveAs(fullPath); ImgPicture.ImageUrl = "~/Profile Pic/@" + FileUpload1.FileName; System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); string fileclass = ""; byte buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); br.Close(); fs.Close(); // only allow images jpg gif bmp png String[] fileType = { "255216", "7173", "6677", "13780" }; for (int i = 0; i < fileType.Length; i++) { if (fileclass == fileType[i]) { isImage = true; break; } } return(isImage); }
public void LoggerDescriptionCustomSerialization() { string className = "Class"; string loggerAssemblyName = "Class"; string loggerFileAssembly = null; string loggerSwitchParameters = "Class"; LoggerVerbosity verbosity = LoggerVerbosity.Detailed; LoggerDescription description = new LoggerDescription(className, loggerAssemblyName, loggerFileAssembly, loggerSwitchParameters, verbosity); MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); BinaryReader reader = new BinaryReader(stream); try { stream.Position = 0; description.WriteToStream(writer); long streamWriteEndPosition = stream.Position; stream.Position = 0; LoggerDescription description2 = new LoggerDescription(); description2.CreateFromStream(reader); long streamReadEndPosition = stream.Position; Assert.Equal(streamWriteEndPosition, streamReadEndPosition); // "Stream end positions should be equal" Assert.Equal(description.Verbosity, description2.Verbosity); // "Expected Verbosity to Match" Assert.Equal(description.LoggerId, description2.LoggerId); // "Expected Verbosity to Match" Assert.Equal(0, string.Compare(description.LoggerSwitchParameters, description2.LoggerSwitchParameters, StringComparison.OrdinalIgnoreCase)); // "Expected LoggerSwitchParameters to Match" Assert.Equal(0, string.Compare(description.Name, description2.Name, StringComparison.OrdinalIgnoreCase)); // "Expected Name to Match" } finally { reader.Close(); writer = null; stream = null; } }
/// <summary> /// 檢查是否為Excel檔 /// </summary> /// <param name="FilePath"></param> /// <returns></returns> private bool CheckXls(string FilePath) { //default sFileName is not Exe or Dll File bool isExcelFile = false; System.IO.FileStream fs = null; System.IO.BinaryReader r = null; string bx = ""; byte buffer; fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); r = new System.IO.BinaryReader(fs); buffer = r.ReadByte(); bx = buffer.ToString(); buffer = r.ReadByte(); bx += buffer.ToString(); buffer = r.ReadByte(); bx += buffer.ToString(); buffer = r.ReadByte(); bx += buffer.ToString(); r.Close(); fs.Close(); if (bx == "20820717224") { isExcelFile = true; } Console.WriteLine(bx); return(isExcelFile); }
public byte[] ReadToByteArray(string fileName) { byte[] _Buffer = null; try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(fileName).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); // close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception ee) { if (IOError != null) { FileProcessorErrorEventArgs x = new FileProcessorErrorEventArgs(ee.Message); IOError(null, x); } } return(_Buffer); }
public override void Read(string file) { // It's compressed pluginHost.Decompress(file); string dec_file; sFolder dec_folder = pluginHost.Get_Files(); if (dec_folder.files is List<sFile>) dec_file = dec_folder.files[0].path; else { string tempFile = Path.GetTempFileName(); Byte[] compressFile = new Byte[(new FileInfo(file).Length) - 0x08]; Array.Copy(File.ReadAllBytes(file), 0x08, compressFile, 0, compressFile.Length); ; File.WriteAllBytes(tempFile, compressFile); pluginHost.Decompress(tempFile); dec_file = pluginHost.Get_Files().files[0].path; } uint file_size = (uint)new FileInfo(dec_file).Length; BinaryReader br = new BinaryReader(File.OpenRead(dec_file)); Byte[] tiles = br.ReadBytes((int)br.BaseStream.Length); br.Close(); Set_Tiles(tiles, 0x40, tiles.Length / 0x40, ColorFormat.colors256, TileForm.Lineal, false); pluginHost.Set_Image(this); }
public static bool IsAllowedExtension(HttpPostedFileBase fu, FileExtension[] fileEx) { int fileLen = fu.ContentLength; byte[] imgArray = new byte[fileLen]; fu.InputStream.Read(imgArray, 0, fileLen); MemoryStream ms = new MemoryStream(imgArray); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); ms.Close(); //注意将文件流指针还原 fu.InputStream.Position = 0; foreach (FileExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) { return(true); } } return(false); }
/// <summary> /// Constructs FAT table from list of sectors /// </summary> /// <param name="hdr">XlsHeader</param> /// <param name="sectors">Sectors list</param> public XlsFat(XlsHeader hdr, List<uint> sectors) { m_hdr = hdr; m_sectors_for_fat = sectors.Count; uint sector = 0, prevSector = 0; int sectorSize = hdr.SectorSize; byte[] buff = new byte[sectorSize]; Stream file = hdr.FileStream; using (MemoryStream ms = new MemoryStream(sectorSize * m_sectors_for_fat)) { lock (file) { for (int i = 0; i < sectors.Count; i++) { sector = sectors[i]; if (prevSector == 0 || (sector - prevSector) != 1) file.Seek((sector + 1) * sectorSize, SeekOrigin.Begin); prevSector = sector; file.Read(buff, 0, sectorSize); ms.Write(buff, 0, sectorSize); } } ms.Seek(0, SeekOrigin.Begin); BinaryReader rd = new BinaryReader(ms); m_sectors = (int)ms.Length / 4; m_fat = new List<uint>(m_sectors); for (int i = 0; i < m_sectors; i++) m_fat.Add(rd.ReadUInt32()); rd.Close(); ms.Close(); } }
public static Shape Load(string fn) { if (!System.IO.File.Exists(fn)) throw new System.Exception("File not found: " + fn); System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream(fn, System.IO.FileMode.Open)); Shape s = new Shape(); s.Width = br.ReadInt32(); s.Height = br.ReadInt32(); s.matrix = new bool[s.Width, s.Height]; try { for (int x = 0; x < s.Width; x++) for (int y = 0; y < s.Height; y++) s.notEmptyCellsCount += (s.matrix[x, y] = br.ReadBoolean()) ? 1 : 0; } catch (System.IO.EndOfStreamException) { throw new System.Exception("Invalid data for shape " + fn); } br.Close(); s.CreateTexture(); return s; }
/// <summary> /// 获得Focus格式图片的长宽 /// </summary> /// <param name="Path"></param> /// <returns></returns> public static Size GetFormatFocusSize(string Path) { BinaryReader br = null; try { br = new BinaryReader(File.OpenRead(Path)); UInt64 wh = (UInt64)br.ReadInt64(); //long length = br.BaseStream.Length; int width = (int)(wh & 0xFFFFFFFF); int height = (int)(wh >> 32); // if (length != width*height + 4) // { // return new Size(-1, -1); // } // else return new Size(width, height); } catch (System.Exception) { return new Size(-1, -1); } finally { if (br != null) { br.Close(); } } }
private void button8_Click(object sender, EventArgs e) { if (listBox3.SelectedIndex == -1) { return; } System.IO.BinaryReader readEvent = new System.IO.BinaryReader(File.OpenRead(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4"))); File.Create(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new").Close(); System.IO.BinaryWriter writeEvent = new System.IO.BinaryWriter(File.OpenWrite(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new")); for (int i = 0; i < (0x10 + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * warpCount + 0x10 * listBox4.SelectedIndex); i++) { writeEvent.Write(readEvent.ReadByte()); // Reads unmodified bytes and writes them to the main file } readEvent.BaseStream.Position += 0x10; for (int i = 0; i < (readEvent.BaseStream.Length - (0x10 + 0x14 * furnitureCount + 0x20 * overworldCount + 0xc * warpCount + 0x10 * listBox4.SelectedIndex + 0x10)); i++) { writeEvent.Write(readEvent.ReadByte()); // Reads unmodified bytes and writes them to the main file } writeEvent.BaseStream.Position = 0xc + furnitureCount * 0x14 + overworldCount * 0x20 + warpCount * 0xc; writeEvent.Write((int)(triggerCount - 1)); readEvent.Close(); writeEvent.Close(); File.Delete(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4")); File.Move(eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4") + "_new", eventPath + "\\" + comboBox1.SelectedIndex.ToString("D4")); comboBox1_SelectedIndexChanged(null, null); }
public static void CopyFileBinary(string srcfilename, string destfilename) { System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open); System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create); System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1); System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2); while (true) { byte[] buf = new byte[1024]; int sz = f1.Read(buf, 0, 1024); if (sz <= 0) { break; } f2.Write(buf, 0, sz); if (sz < 10240) { break; // eof reached } } f1.Close(); f2.Close(); }