public void Load(BinaryReader br, FileStream fs) { Offset = br.ReadInt32(); Offset += 16; FrameCount = br.ReadInt32(); MipWidth = br.ReadInt32(); MipHeight = br.ReadInt32(); StartX = br.ReadInt32(); StartY = br.ReadInt32(); TileCount = br.ReadUInt16(); TotalCount = br.ReadUInt16(); CellWidth = br.ReadUInt16(); CellHeight = br.ReadUInt16(); Frames = new EanFrame[TotalCount]; long curPos = fs.Position; fs.Seek((long)Offset, SeekOrigin.Begin); for (int i = 0; i < TotalCount; i++) { Frames[i].X = br.ReadUInt16(); Frames[i].Y = br.ReadUInt16(); Frames[i].Width = br.ReadUInt16(); Frames[i].Height = br.ReadUInt16(); } fs.Seek((long)curPos, SeekOrigin.Begin); }
private bool CheckMpgFile(string fileName) { try { if (!File.Exists(fileName)) { return false; } using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (BinaryReader reader = new BinaryReader(stream)) { stream.Seek(0, SeekOrigin.Begin); byte[] header = reader.ReadBytes(5); if (header[0] != 0 || header[1] != 0 || header[2] != 1 || header[3] != 0xba) { return false; } if ((header[4] & 0x40) == 0) { return false; } stream.Seek(0x800, SeekOrigin.Begin); header = reader.ReadBytes(5); if (header[0] != 0 || header[1] != 0 || header[2] != 1 || header[3] != 0xba) { return false; } if ((header[4] & 0x40) == 0) { return false; } stream.Seek(0x8000, SeekOrigin.Begin); header = reader.ReadBytes(5); if (header[0] != 0 || header[1] != 0 || header[2] != 1 || header[3] != 0xba) { return false; } if ((header[4] & 0x40) == 0) { return false; } return true; } } } catch (Exception e) { // If an IOException is raised, the file may be in use/being recorded so we assume that it is a correct mpeg file // This fixes replaying mpeg files while being recorded if (e.GetType().ToString() == "System.IO.IOException") { return true; } Log.Info("Exception in CheckMpgFile with message: {0}", e.Message); } return false; }
private bool FindDataChunk(out long dataPos, out long dataSize) { bool done = false; FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[12]; // 12 bytes = Size of Chunk Header UInt32 chunkType = 0, chunkSize = 0; dataPos = 0; dataSize = 0; UInt32 dataSpecifier = BitConverter.ToUInt32(CAFReader.StringToByteArray("data"),0); long bytesRead = stream.Seek(8, SeekOrigin.Begin); // skip file header while (!done && bytesRead > 0) { bytesRead = stream.Read(buffer, 0, 12); chunkType = ((UInt32)(buffer[3]) << 24) + ((UInt32)(buffer[2]) << 16) + ((UInt32)(buffer[1]) << 8) + buffer[0]; Console.WriteLine("Chunktype: {0}", CAFReader.ByteArrayToString(BitConverter.GetBytes(chunkType))); if (chunkType == dataSpecifier) { dataPos = stream.Position+4; // skip edits dataSize = ((UInt32)(buffer[8]) << 24) + ((UInt32)(buffer[9]) << 16) + ((UInt32)(buffer[10]) << 8) + buffer[11]; dataSize -= 4; // edits included in size done = true; } else { chunkSize = ((UInt32)(buffer[8]) << 24) + ((UInt32)(buffer[9]) << 16) + ((UInt32)(buffer[10]) << 8) + buffer[11]; stream.Seek(chunkSize, SeekOrigin.Current); } } stream.Close(); return done; }
public virtual Stream GetDataInputStream(CompressionType compression) { try { switch (compression) { case CompressionType.None: using (FileStream fstr = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { long length = fstr.Seek(0, SeekOrigin.End); fstr.Seek(0, SeekOrigin.Begin); byte[] data = new byte[length]; fstr.Read(data, 0, data.Length); return new MemoryStream(data); } case CompressionType.GZip: Stream stream1 = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return new GZipStream(stream1, CompressionMode.Decompress); case CompressionType.Zlib: Stream stream2 = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return new ZlibStream(stream2, CompressionMode.Decompress); case CompressionType.Deflate: Stream stream3 = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return new DeflateStream(stream3, CompressionMode.Decompress); default: throw new ArgumentException("Invalid CompressionType specified", "compression"); } } catch (Exception ex) { throw new NbtIOException("Failed to open compressed NBT data stream for input.", ex); } }
/// <summary> /// Reads and parses the specified addon file. /// </summary> /// <param name="stream">The file stream representing the addon file.</param> /// <exception cref="System.IO.IOException">Any sort of error regarding reading from the provided stream.</exception> /// <exception cref="ReaderException">Errors parsing the file</exception> public Reader(FileStream stream) : this() { try { // Seek and read a byte to test access to the stream. stream.Seek(0, SeekOrigin.Begin); stream.ReadByte(); stream.Seek(0, SeekOrigin.Begin); Buffer = stream; } catch (IOException) { throw; } try { Parse(); } catch (ReaderException) { throw; } }
public static ObjectInfo[] ReadCollection(string path) { Stream stream = new FileStream(path, FileMode.Open); BinaryReader binaryReader = new BinaryReader(stream); int count = binaryReader.ReadInt32(); ObjectInfo[] infoCollection = new ObjectInfo[count]; infoCollection[0] = new ObjectInfo { height = 0, indices = new int[0] }; for (int index = 0; index < count; ++index) { if (index == 0) { ObjectInfo info = infoCollection[index] = new ObjectInfo(); info.height = binaryReader.ReadByte(); info.indices = new int[info.height]; info.indices[0] = binaryReader.ReadByte(); stream.Seek(6, SeekOrigin.Current); } else { ObjectInfo info = infoCollection[index] = new ObjectInfo(); info.height = binaryReader.ReadByte(); info.indices = new int[info.height]; for (int subIndex = 0; subIndex < info.height; subIndex++) info.indices[subIndex] = binaryReader.ReadUInt16(); Array.Reverse(info.indices); stream.Seek(6, SeekOrigin.Current); } } binaryReader.Close(); stream.Dispose(); return infoCollection; }
private static MachineType GetDllMachineType(string fullPath) { FileStream fs = null; BinaryReader br = null; try { fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read); br = new BinaryReader(fs); fs.Seek(0x3c, SeekOrigin.Begin); Int32 peOffset = br.ReadInt32(); fs.Seek(peOffset, SeekOrigin.Begin); UInt32 peHead = br.ReadUInt32(); if (peHead != 0x00004550) // "PE00" little-endian { throw new Exception("Unable to find PE header in " + fullPath); } MachineType type = (MachineType)br.ReadUInt16(); return type; } finally { if (br != null) br.Close(); if (fs != null) fs.Close(); } }
/// <summary> /// 获取指定文件的架构位数 523-64位, 267-32位/AnyCpu /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static ushort GetPEArchitecture(string filePath) { ushort architecture = 0; try { using (System.IO.FileStream fStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) //check the MZ signature { //Any CPU PE32 with 32BIT = 0 //x86 PE32 with 32BIT = 1 //x64 / Itanium(IA - 64) PE32 + with 32BIT = 0 fStream.Seek(0x3A, System.IO.SeekOrigin.Current); //seek to e_lfanew. fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); //seek to the start of the NT header. if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature. { fStream.Seek(20, System.IO.SeekOrigin.Current); //seek past the file header, architecture = bReader.ReadUInt16(); //read the magic number of the optional header. } } } } } catch (Exception ex) { /* TODO: Any exception handling you want to do, personally I just take 0 as a sign of failure */ } //if architecture returns 0, there has been an error. return(architecture); }
public static CpuArchitectures GetPEArchitecture(string pFilePath) { ushort architecture = 0; ushort[] coffHeader = new ushort[10]; using (FileStream fStream = new FileStream(pFilePath, FileMode.Open, FileAccess.Read)) { using (BinaryReader bReader = new BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) //check the MZ signature { fStream.Seek(0x3A, SeekOrigin.Current); // Go to the location of the location of the NT header fStream.Seek(bReader.ReadUInt32(), SeekOrigin.Begin); // seek to the start of the NT header. if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature. { for (int i = 0; i < 10; i++) // Read COFF Header coffHeader[i] = bReader.ReadUInt16(); if (coffHeader[8] > 0) // Read Optional Header architecture = bReader.ReadUInt16(); } } } } switch (architecture) { case 0x20b: return CpuArchitectures.x64; case 0x10b: return ((coffHeader[9] & 0x100) == 0) ? CpuArchitectures.AnyCpu : CpuArchitectures.x86; default: return CpuArchitectures.Unknown; } }
public static MachineType GetMachineType(string path) { // Open the PE File as a binary file, and parse just enough information to determine the // machine type. //http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx using (SafeFileHandle safeHandle = NativeMethods.CreateFile( path, NativeAccessFlags.GenericRead, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero)) { FileStream fs = new FileStream(safeHandle, FileAccess.Read); using (BinaryReader br = new BinaryReader(fs)) { fs.Seek(0x3c, SeekOrigin.Begin); Int32 peOffset = br.ReadInt32(); fs.Seek(peOffset, SeekOrigin.Begin); UInt32 peHead = br.ReadUInt32(); if (peHead != 0x00004550) // "PE\0\0", little-endian throw new Exception("Can't find PE header"); return (MachineType)br.ReadUInt16(); } } }
private static List<FilePathInfo> pathList = new List<FilePathInfo>();//递归过程中解析出来的文件列表 private static void MakeCach(string vfsPath) { FileStream fs = new FileStream(vfsPath, FileMode.OpenOrCreate); BinaryReader br = new BinaryReader(fs); int baseOff = br.ReadInt32(); int nowIndex = 4; while (nowIndex < baseOff) { int pathLen = br.ReadByte(); byte[] data = br.ReadBytes(pathLen); string pathA = Encoding.ASCII.GetString(data); int imgStart = br.ReadInt32(); int imgEnd = br.ReadInt32(); nowIndex += 9 + pathLen; fs.Seek(imgStart + baseOff, SeekOrigin.Begin); byte[] img = br.ReadBytes(imgEnd - imgStart); dataDict[pathA] = img; fs.Seek(nowIndex, SeekOrigin.Begin); } br.Close(); fs.Close(); }
/// <summary> /// Check current file stream postion for header /// use this only if current position byte = 0x1F /// </summary> /// <param name="fs">The stream to check.</param> /// <returns>Returns true if the stream a valid gzip header at the current position.</returns> public static bool IsGZipHeader(FileStream fs) { // Read the first ten bytes of the stream byte[] header = new byte[HeaderLength - 1]; int bytesRead = fs.Read(header, 0, header.Length); fs.Seek(-bytesRead, SeekOrigin.Current); if (bytesRead < header.Length) { return false; } // Check the id tokens and compression algorithm if (header[0] != 0x8B || header[1] != 0x8) { return false; } // Extract the GZIP flags, of which only 5 are allowed (2 pow. 5 = 32) if (header[2] > 32) { return false; } // Check the extra compression flags, which is either 2 or 4 with the Deflate algorithm if (header[7] != 0x0 && header[7] != 0x2 && header[7] != 0x4) { return false; } fs.Seek(-1, SeekOrigin.Current); return true; }
public PEOptionalHeader(FileStream fs) { MagicNumber = Utils.ReadShort(fs); //Skips if (MagicNumber == MAGIC_NUMBER_PE32) fs.Seek(90, SeekOrigin.Current); else fs.Seek(106, SeekOrigin.Current); NumberOfRvAndSizes = Utils.ReadInt(fs); DataDirectories = new List<PEDataDirectory>(); if (NumberOfRvAndSizes < 16) throw new Exception("Bad format, expected at least 16 directories"); DataDirectories.Add(new PEDataDirectory(fs,EXPORT_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,IMPORT_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,RESOURCE_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,EXCEPTION_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,CERTIFICATE_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,BASE_RELOCATION_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,DEBUG)); DataDirectories.Add(new PEDataDirectory(fs,ARCHITECTURE)); DataDirectories.Add(new PEDataDirectory(fs,GLOBAL_PTR)); DataDirectories.Add(new PEDataDirectory(fs,TLS_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,LOAD_CONFIG_TABLE)); DataDirectories.Add(new PEDataDirectory(fs,BOUND_IMPORT)); DataDirectories.Add(new PEDataDirectory(fs,IAT)); DataDirectories.Add(new PEDataDirectory(fs,DELAY_IMPORT_DESCRIPTOR)); DataDirectories.Add(new PEDataDirectory(fs,CLR_RUNTIME_HEADER)); DataDirectories.Add(new PEDataDirectory(fs,RESERVED)); for (int i = 16; i < NumberOfRvAndSizes; i++) DataDirectories.Add(new PEDataDirectory(fs, "Unknown")); }
public static bool GetPackedAssembly(string fileName, out byte[] outBytes) { FileStream input = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); int length = (int)input.Length; input.Seek(60L, SeekOrigin.Begin); BinaryReader reader = new BinaryReader(input); int read = reader.ReadInt32(); if ((read >= 2) && (read <= (length - 512))) { input.Seek((long)read, SeekOrigin.Begin); if (reader.ReadUInt32() == 17744) { read += 348; input.Seek((long)read, SeekOrigin.Begin); int read2 = reader.ReadInt32(); if ((read2 < length) && (read2 >= 768)) { read2 += 16; length -= read2; byte[] buffer = new byte[length]; input.Seek((long)read2, SeekOrigin.Begin); input.Read(buffer, 0, length); input.Close(); if (UnpackBytes(buffer, out outBytes, length)) { return true; } } } } outBytes = null; return false; }
public static void Initialize() { string path = Files.GetFilePath("skillgrp.mul"); List = new List<SkillGroup>(); SkillList = new List<int>(); if (path != null) { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var bin = new BinaryReader(fs)) { int start = 4; int strlen = 17; int count = bin.ReadInt32(); if (count == -1) { unicode = true; count = bin.ReadInt32(); start *= 2; strlen *= 2; } List.Add(new SkillGroup("Misc")); for (int i = 0; i < count - 1; ++i) { int strbuild; fs.Seek((start + (i * strlen)), SeekOrigin.Begin); var builder2 = new StringBuilder(17); if (unicode) { while ((strbuild = bin.ReadInt16()) != 0) { builder2.Append((char)strbuild); } } else { while ((strbuild = bin.ReadByte()) != 0) { builder2.Append((char)strbuild); } } List.Add(new SkillGroup(builder2.ToString())); } fs.Seek((start + ((count - 1) * strlen)), SeekOrigin.Begin); try { while (bin.BaseStream.Length != bin.BaseStream.Position) { SkillList.Add(bin.ReadInt32()); } } catch // just for safety { } } } } }
public Metadata(FileStream fs) { fs.Seek(0, SeekOrigin.Begin); PDB = new PDBHeader(fs); PDH = new PalmDOCHeader(fs); mobiHeader = new MobiHead(fs, PDB.MobiHeaderSize); // Use ASIN of the first book in the mobi _ASIN = mobiHeader.exthHeader.ASIN != "" ? mobiHeader.exthHeader.ASIN : mobiHeader.exthHeader.ASIN2; // Start at end of first book records, search for a second (KF8) and use it instead (for combo books) for (int i = PDH.RecordCount; i < PDB.NumRecords - 1; i++) { uint recSize = PDB._recInfo[i + 1].RecordDataOffset - PDB._recInfo[i].RecordDataOffset; if (recSize < 8) continue; byte[] buffer = new byte[recSize]; fs.Seek(PDB._recInfo[i].RecordDataOffset, SeekOrigin.Begin); fs.Read(buffer, 0, buffer.Length); if (Encoding.ASCII.GetString(buffer, 0, 8) == "BOUNDARY") { _startRecord = i + 2; PDH = new PalmDOCHeader(fs); mobiHeader = new MobiHead(fs, PDB.MobiHeaderSize); break; } } }
public void SeekAppendModifyThrows() { string fileName = GetTestFilePath(); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { fs.Write(TestBuffer, 0, TestBuffer.Length); } using (FileStream fs = new FileStream(fileName, FileMode.Append)) { long length = fs.Length; Assert.Throws<IOException>(() => fs.Seek(length - 1, SeekOrigin.Begin)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.End)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(0, SeekOrigin.Begin)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.Current)); Assert.Equal(length, fs.Position); Assert.Throws<IOException>(() => fs.Seek(-length, SeekOrigin.End)); Assert.Equal(length, fs.Position); } }
bool IsX86Architecture(string filePath) { ushort architecture = 0; try { using (System.IO.FileStream fStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) { fStream.Seek(0x3A, System.IO.SeekOrigin.Current); fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); if (bReader.ReadUInt32() == 17744) { fStream.Seek(20, System.IO.SeekOrigin.Current); architecture = bReader.ReadUInt16(); } } } } } catch { } if (architecture == 0x10b) { return(true); } else { return(false); } }
/// <summary> /// 获取文件MD5 /// </summary> /// <param name="filePath"></param> /// <param name="type"></param> /// <returns></returns> public static string getMd5Hash(string filePath, int type) { string smd5 = filePath; try { using (FileStream t = new FileStream(filePath, FileMode.Open)) { int l = 1024; long l1 = t.Length / 3; long l2 = t.Length / 2; if (l1 < l) { l = (int)l1; } byte[] begin = new byte[l]; byte[] middle = new byte[l]; byte[] end = new byte[l]; t.Seek(0, SeekOrigin.Begin); t.Read(begin, 0, begin.Length); t.Seek(l2, SeekOrigin.Begin); t.Read(middle, 0, middle.Length); t.Seek(t.Length - end.Length, SeekOrigin.Begin); t.Read(end, 0, end.Length); string body = UnTo.byteToIntStr(begin) + UnTo.byteToIntStr(middle) + UnTo.byteToIntStr(end); return getMd5Hash(body); } } catch { return getMd5Hash(filePath); } }
public void RaceSfv() { CleanTestFilesOutput(); Race race = UploadSfvFile (); FileInfo fileInfo = new FileInfo (Misc.PathCombine (race.CurrentRaceData.DirectoryPath, Config.FileNameRace)); using (FileStream stream = new FileStream (fileInfo.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { using (BinaryReader reader = new BinaryReader (stream)) { stream.Seek (0, SeekOrigin.Begin); Assert.AreEqual (4, reader.ReadInt32 (), "Expected integer value (4)"); stream.Seek(256 * 1, SeekOrigin.Begin); Assert.AreEqual("infected.part1.rar", reader.ReadString(), "infected.part1.rar"); Assert.AreEqual("2e04944c", reader.ReadString(), "2e04944c"); Assert.AreEqual(false, reader.ReadBoolean(), "FileUploaded"); stream.Seek(256 * 2, SeekOrigin.Begin); Assert.AreEqual("infected.part2.rar", reader.ReadString(), "infected.part2.rar"); Assert.AreEqual("1c7c24a5", reader.ReadString(), "1c7c24a5"); Assert.AreEqual(false, reader.ReadBoolean(), "FileUploaded"); stream.Seek(256 * 3, SeekOrigin.Begin); Assert.AreEqual("infected.part3.rar", reader.ReadString(), "infected.part3.rar"); Assert.AreEqual("d5d617e3", reader.ReadString(), "d5d617e3"); Assert.AreEqual(false, reader.ReadBoolean(), "FileUploaded"); stream.Seek(256 * 4, SeekOrigin.Begin); Assert.AreEqual("infected.part4.rar", reader.ReadString(), "infected.part4.rar"); Assert.AreEqual("0edb20ea", reader.ReadString(), "0edb20ea"); Assert.AreEqual(false, reader.ReadBoolean(), "FileUploaded"); } } }
public static bool Is64BitNativeDll(string filePath) { if (!System.IO.File.Exists(filePath)) { return(false); } ushort architecture = 0; using (System.IO.FileStream fStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) { fStream.Seek(0x3A, System.IO.SeekOrigin.Current); fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); if (bReader.ReadUInt32() == 17744) { fStream.Seek(20, System.IO.SeekOrigin.Current); architecture = bReader.ReadUInt16(); } } } } return(architecture == 0x20b); }
public CabeceraSF(string fichero) { FileStream reader = null; try{ reader = new FileStream (fichero, FileMode.Open); reader.Seek(4,SeekOrigin.Begin); int contador = 4; do{ contador++; }while ((contador < LIMITE) && (contador < reader.Length) && (reader.ReadByte()!= 0)); //TODO: Poner limite al while reader.Seek(0, SeekOrigin.Begin); byte[] b = new byte[contador]; reader.Read (b, 0, contador); if ((b[0]!=0x53) || (b[1]!=0x46) || (b[2]!=0) || (b[3]!=0) || (b[4] != 6)){ // TODO: Poner una excepcion personalizada throw new Exception(); } numero = b[5]; nombre = ""; for (int i=6; (i < b.Length) && (b[i]!=0); i++) nombre += Convert.ToChar(b[i]); } catch (Exception){ throw; } finally{ if (reader != null){ reader.Close(); } } }
public void FlushSetLengthAtEndOfBuffer() { // This is a regression test for a bug with FileStream’s Flush() // and SetLength() methods. // The read-buffer was not flushed inside Flush and SetLength when // the buffer pointer was at the end. This causes subsequent Seek // and Read calls to operate on stale/wrong data. // customer reported repro using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.SetLength(200); fs.Flush(); // write 119 bytes starting from Pos = 28 fs.Seek(28, SeekOrigin.Begin); Byte[] buffer = new Byte[119]; for (int i = 0; i < buffer.Length; i++) buffer[i] = Byte.MaxValue; fs.Write(buffer, 0, buffer.Length); fs.Flush(); // read 317 bytes starting from Pos = 84; fs.Seek(84, SeekOrigin.Begin); fs.Read(new byte[1024], 0, 317); fs.SetLength(135); fs.Flush(); // read one byte at Pos = 97 fs.Seek(97, SeekOrigin.Begin); Assert.Equal(fs.ReadByte(), (int)Byte.MaxValue); } }
public static ushort GetPEArchitecture(string pFilePath) { ushort architecture = 0; try { using (System.IO.FileStream fStream = new System.IO.FileStream(pFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream)) { if (bReader.ReadUInt16() == 23117) //check the MZ signature { fStream.Seek(0x3A, System.IO.SeekOrigin.Current); //seek to e_lfanew. fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin); //seek to the start of the NT header. if (bReader.ReadUInt32() == 17744) //check the PE\0\0 signature. { fStream.Seek(20, System.IO.SeekOrigin.Current); //seek past the file header, architecture = bReader.ReadUInt16(); //read the magic number of the optional header. } } } } } catch (Exception) { return(0); } //if architecture returns 0, there has been an error. return(architecture); }
public static string CreateZIPFile(string path, int M, string strsuff) { try { Crc32 crc = new Crc32();//未压缩的 ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipout = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(path + ".zip")); //ICSharpCode.SharpZipLib.GZip.GZipOutputStream zipout = new GZipOutputStream(System.IO.File.Create(path+ ".zip")); System.IO.FileStream fs = System.IO.File.OpenRead(path + strsuff); long pai = 1024 * 1024 * M;//每M兆写一次 long forint = fs.Length / pai + 1; byte[] buffer = null; zipout.SetLevel(7); ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(path + strsuff)); entry.Size = fs.Length; entry.DateTime = DateTime.Now; zipout.PutNextEntry(entry); //zipout. for (long i = 1; i <= forint; i++) { if (pai * i < fs.Length) { buffer = new byte[pai]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } else { if (fs.Length < pai) { buffer = new byte[fs.Length]; } else { buffer = new byte[fs.Length - pai * (i - 1)]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } } fs.Read(buffer, 0, buffer.Length); crc.Reset(); crc.Update(buffer); zipout.Write(buffer, 0, buffer.Length); zipout.Flush(); } fs.Close(); zipout.Finish(); zipout.Close(); System.IO.File.Delete(path + strsuff); // File.Create(path.Replace(".doc","") + ".zip",buffer.Length); return(path + ".zip"); } catch (Exception ex) { string str = ex.Message; return(path); } }
public static long GetUncompressedSize(FileStream stream) { long prev = stream.Position; stream.Seek (-4, SeekOrigin.End); byte[] a = new byte[4]; stream.Read (a, 0, 4); stream.Seek (prev, SeekOrigin.Begin); return UtArrays.LeerInt32 (a, 0); }
public PalmDOCHeader(FileStream fs) { fs.Read(_compression, 0, _compression.Length); fs.Seek(2, SeekOrigin.Current); fs.Read(_textLength, 0, _textLength.Length); fs.Read(_recordCount, 0, _recordCount.Length); fs.Read(_recordSize, 0, _recordSize.Length); fs.Read(_encryptionType, 0, _encryptionType.Length); fs.Seek(2, SeekOrigin.Current); }
//this is only here for testing purposes, this needs to be moved public bool BlankPassword(PSTFile pst) { var toMatch = new byte[] {0xFF, 0x67}; foreach (var entry in this.DataEntries) if (entry.Key[0] == toMatch[0] && entry.Key[1] == toMatch[1]) { pst.CloseMMF(); //DatatEncoder.CryptPermute(ref this._data.Parent.Data, this._data.Parent.Data.Length, true); using (var stream = new FileStream(pst.Path, FileMode.Open)) { var dataBlockOffset = entry.DataOffset; //this._data.Parent.Data[dataBlockOffset] = 0x00; //this._data.Parent.Data[dataBlockOffset + 1] = 0x00; this._data.Parent.Data[dataBlockOffset + 2] = 0x00; this._data.Parent.Data[dataBlockOffset + 3] = 0x00; this._data.Parent.Data[dataBlockOffset + 4] = 0x00; this._data.Parent.Data[dataBlockOffset + 5] = 0x00; DatatEncoder.CryptPermute(this._data.Parent.Data, this._data.Parent.Data.Length, true, pst); var testCRC = (new CRC32()).ComputeCRC(0, this._data.Parent.Data, (uint)this._data.Parent.Data.Length); stream.Seek((long)(this._data.Parent.PstOffset + entry.DataOffset), SeekOrigin.Begin); stream.Write( new [] { //this._data.Parent.Data[dataBlockOffset], //this._data.Parent.Data[dataBlockOffset + 1], this._data.Parent.Data[dataBlockOffset + 2], this._data.Parent.Data[dataBlockOffset + 3], this._data.Parent.Data[dataBlockOffset + 4], this._data.Parent.Data[dataBlockOffset + 5] }, 0, 4); var newCRC = (new CRC32()).ComputeCRC(0, this._data.Parent.Data, (uint) this._data.Parent.Data.Length); DatatEncoder.CryptPermute(this._data.Parent.Data, this._data.Parent.Data.Length, false, pst); var crcoffset = (int) (this._data.Parent.PstOffset + this._data.Parent.CRCOffset); stream.Seek(crcoffset, SeekOrigin.Begin); var temp = BitConverter.GetBytes(newCRC); stream.Write(new [] { temp[0],temp[1],temp[2],temp[3] }, 0, 4); } pst.OpenMMF(); return true; } return false; }
void InitializeBlocks() { uint fileOffset = 0; bool hasEnded = false; List <Block> result = new List <Block> (); ulong counter = 0; byte [] header = new byte [BlockData.BLOCK_HEADER_SIZE]; ProfilerEventHandler eventProcessor = new ProfilerEventHandler(); while (!hasEnded) { int bytesRead = stream.Read(header, 0, BlockData.BLOCK_HEADER_SIZE); if (bytesRead != BlockData.BLOCK_HEADER_SIZE) { if (bytesRead == 0) { Console.WriteLine("WARNING: File truncated at offset {0} without end block", fileOffset); break; } else { throw new Exception(String.Format("At file offset {0} block header is not complete", fileOffset)); } } fileOffset += (uint)BlockData.BLOCK_HEADER_SIZE; counter += BlockData.DecodeHeaderBlockCounterDelta(header); Block block = new Block(fileOffset, BlockData.DecodeHeaderBlockCode(header), (uint)BlockData.DecodeHeaderBlockLength(header), counter); result.Add(block); fileOffset += block.Length; stream.Seek(fileOffset, SeekOrigin.Begin); if (block.Code == BlockCode.INTRO) { ReadBlock(block).Decode(eventProcessor); startCounter = eventProcessor.StartCounter; startTime = eventProcessor.StartTime; } if (block.Code == BlockCode.END) { hasEnded = true; ReadBlock(block).Decode(eventProcessor); endCounter = eventProcessor.EndCounter; endTime = eventProcessor.EndTime; } } blocks = result.ToArray(); foreach (Block block in blocks) { block.TimeFromStart = eventProcessor.ClicksToTimeSpan(block.Counter); } }
public PEFileHeader(int offset,FileStream fs) { this.Offset = offset; // skip past header items we don't care about fs.Seek(6, SeekOrigin.Current); NumSections = Utils.ReadShort(fs); // find the size of the optional header from the file header fs.Seek(12, SeekOrigin.Current); OptionalHeaderSize = Utils.ReadShort(fs); fs.Seek(2, SeekOrigin.Current); }
public static void ApplyIPSPatch(string romname, string patchname) { // Noobish Noobsicle wrote this IPS patching code // romname is the original ROM, patchname is the patch to apply FileStream romstream = new FileStream(romname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); FileStream ipsstream = new FileStream(patchname, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); int lint = (int)ipsstream.Length; byte[] ipsbyte = new byte[ipsstream.Length]; byte[] rombyte = new byte[romstream.Length]; IAsyncResult romresult; IAsyncResult ipsresult = ipsstream.BeginRead(ipsbyte, 0, lint, null, null); ipsstream.EndRead(ipsresult); int ipson = 5; int totalrepeats = 0; int offset = 0; bool keepgoing = true; while (keepgoing == true) { offset = ipsbyte[ipson] * 0x10000 + ipsbyte[ipson + 1] * 0x100 + ipsbyte[ipson + 2]; ipson++; ipson++; ipson++; if (ipsbyte[ipson] * 256 + ipsbyte[ipson + 1] == 0) { ipson++; ipson++; totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; byte[] repeatbyte = new byte[totalrepeats]; for (int ontime = 0; ontime < totalrepeats; ontime++) repeatbyte[ontime] = ipsbyte[ipson]; romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(repeatbyte, 0, totalrepeats, null, null); romstream.EndWrite(romresult); ipson++; } else { totalrepeats = ipsbyte[ipson] * 256 + ipsbyte[ipson + 1]; ipson++; ipson++; romstream.Seek(offset, SeekOrigin.Begin); romresult = romstream.BeginWrite(ipsbyte, ipson, totalrepeats, null, null); romstream.EndWrite(romresult); ipson = ipson + totalrepeats; } if (ipsbyte[ipson] == 69 && ipsbyte[ipson + 1] == 79 && ipsbyte[ipson + 2] == 70) keepgoing = false; } romstream.Close(); ipsstream.Close(); }
private static byte[] GetAesKeyFromZlz(FileStream zlzStream) { byte[] aes = new byte[32]; zlzStream.Seek(0x10060, SeekOrigin.Begin); for (int i = 0; i < 8; i++) { zlzStream.Read(aes, i * 4, 4); zlzStream.Seek(12, SeekOrigin.Current); } return aes; }
public void SeekDisposedThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.Dispose(); Assert.Throws<ObjectDisposedException>(() => fs.Seek(1, SeekOrigin.Begin)); // no fast path Assert.Throws<ObjectDisposedException>(() => fs.Seek(fs.Position, SeekOrigin.Begin)); // parameter checking happens first Assert.Throws<ArgumentException>("origin", () => fs.Seek(0, ~SeekOrigin.Begin)); } }
/// <summary> /// Reads just the content requested in order to satisfy the paging ability of VirtualMode for the DataGridView /// </summary> /// <param name="lowerPageBoundary"></param> /// <param name="rowsPerPage"></param> /// <returns></returns> public DataTable SupplyPageOfData(int lowerPageBoundary, int rowsPerPage) { FileStream myStream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 100000); BinaryReader myReader = new BinaryReader(myStream); try { FileInfo fi = new FileInfo(_fileName); // Encoding appears to be ASCII, not Unicode myStream.Seek(_headerLength + 1, SeekOrigin.Begin); if ((int)fi.Length == _headerLength) { // The file is empty, so we are done here return null; } int maxRawRow = (int)((fi.Length - (HeaderLength + 1)) / _recordLength); int strt = GetFileIndex(lowerPageBoundary); int end = GetFileIndex(lowerPageBoundary + rowsPerPage); int rawRows = end - strt; int length = rawRows * _recordLength; long offset = strt * _recordLength; myStream.Seek(offset, SeekOrigin.Current); byte[] byteContent = myReader.ReadBytes(length); if (byteContent.Length < length) { length = byteContent.Length; } char[] characterContent = new char[length]; Encoding.Default.GetChars(byteContent, 0, length, characterContent, 0); DataTable result = new DataTable(); foreach (Field field in _columns) { result.Columns.Add(new Field(field.ColumnName, field.TypeCharacter, field.Length, field.DecimalCount)); } int start = 0; for (int row = lowerPageBoundary; row < lowerPageBoundary + rowsPerPage; row++) { if (row > maxRawRow) break; result.Rows.Add(ReadTableRow(GetFileIndex(row) - strt, start, characterContent, result)); start += _recordLength; } return result; } finally { myReader.Close(); } }
internal static TextWriter CreateFileAppender(string fileName, Encoding encode, bool correctEnd, bool disposeStream) { TextWriter res; if (correctEnd) { FileStream fs = null; try { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fs.Length >= 2) { fs.Seek(-2, SeekOrigin.End); if (fs.ReadByte() == 13) { if (fs.ReadByte() == 10) { int nowRead; do { fs.Seek(-2, SeekOrigin.Current); nowRead = fs.ReadByte(); } while (nowRead == 13 || nowRead == 10); } } else fs.ReadByte(); fs.WriteByte(13); fs.WriteByte(10); } res = new StreamWriter(fs, encode); } finally { if (disposeStream && fs != null) fs.Close(); } } else { res = new StreamWriter(fileName, true, encode); } return res; }
/// <summary> /// 取得一个文本文件流的编码方式。 /// </summary> /// <param name="stream">文本文件流。</param> /// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param> /// <returns></returns> /// public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding) { Encoding targetEncoding = defaultEncoding; if (stream != null && stream.Length >= 2) { //保存文件流的前4个字节 byte byte1 = 0; byte byte2 = 0; byte byte3 = 0; byte byte4 = 0; //保存当前Seek位置 long origPos = stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin); int nByte = stream.ReadByte(); byte1 = Convert.ToByte(nByte); byte2 = Convert.ToByte(stream.ReadByte()); if (stream.Length >= 3) { byte3 = Convert.ToByte(stream.ReadByte()); } if (stream.Length >= 4) { byte4 = Convert.ToByte(stream.ReadByte()); } //根据文件流的前4个字节判断Encoding //Unicode {0xFF, 0xFE}; //BE-Unicode {0xFE, 0xFF}; //UTF8 = {0xEF, 0xBB, 0xBF}; if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe { targetEncoding = Encoding.BigEndianUnicode; } if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode { targetEncoding = Encoding.Unicode; } if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8 { targetEncoding = Encoding.UTF8; } //恢复Seek位置 stream.Seek(origPos, SeekOrigin.Begin); } return targetEncoding; }
// read / write public byte[] ReadSector(int lba) { CheckReady(); CheckLBA(lba); byte[] sector = new byte[BYTES_PER_SECTOR]; stream.Seek(lba * BYTES_PER_SECTOR, SeekOrigin.Begin); if (stream.Read(sector, 0, BYTES_PER_SECTOR) != BYTES_PER_SECTOR) { throw new Exception("Failed to read all bytes for sector"); } return(sector); }
private static int SplitFiles(string fileName, int nChunks, int ramCapacityInBytes, int lastChunkSize, string folderPath) { byte[] byteArray = new byte[ramCapacityInBytes]; int offset = 0; SortBase sortAlgo = new QuickSort(); using (System.IO.FileStream stream = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) { for (int i = 0; i < nChunks; i++) { stream.Seek(offset, System.IO.SeekOrigin.Begin); stream.Read(byteArray, 0, ramCapacityInBytes); int[] intArray = ConvertToInt(byteArray); sortAlgo.Sort(intArray); string savedFileName = WriteToFile(intArray, i, folderPath); Console.WriteLine(string.Format("File {0} Size {1} bytes ({2})", i, ramCapacityInBytes, savedFileName)); offset += ramCapacityInBytes; } if (lastChunkSize > 0) { byteArray = new byte[lastChunkSize]; stream.Seek(offset, System.IO.SeekOrigin.Begin); stream.Read(byteArray, 0, lastChunkSize); int[] intArray = ConvertToInt(byteArray); sortAlgo.Sort(intArray); string savedFileName = WriteToFile(intArray, nChunks, folderPath); Console.WriteLine(string.Format("File {0} Size {1} bytes ({2})", nChunks, lastChunkSize, savedFileName)); nChunks += 1; } } return(nChunks); }
private void button8_Click(object sender, EventArgs e) { Image slika; FileStream stream; var client = new MongoClient("mongodb://localhost"); var database = client.GetDatabase("docs"); var fs = new GridFSBucket(database); OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { stream = new System.IO.FileStream(ofd.FileName, FileMode.Open, FileAccess.Read); slika = Image.FromStream(stream); GridFSUploadOptions opcije = new GridFSUploadOptions(); opcije.ContentType = "image/jpg"; opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length); int duzina = Convert.ToInt32(stream.Length); byte[] bajtovi = new byte[duzina]; stream.Seek(0, SeekOrigin.Begin); int bytesRead = stream.Read(bajtovi, 0, duzina); fs.UploadFromBytes("Test", bajtovi, opcije); } MessageBox.Show("done"); }
public async Task <string> CaptureAndSaveAsync() { if (!(await RequestStoragePermission())) { var missingPermissions = string.Join(", ", nameof(StoragePermission)); throw new Exception($"{missingPermissions} permission(s) are required."); } var bytes = await CaptureAsync(); Java.IO.File picturesFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim); string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); try { string filePath = System.IO.Path.Combine(picturesFolder.AbsolutePath + "/Camera", "Screnshot-" + date + ".png"); using (System.IO.FileStream SourceStream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate)) { SourceStream.Seek(0, System.IO.SeekOrigin.End); await SourceStream.WriteAsync(bytes, 0, bytes.Length); } return(filePath); } catch (Exception ex) { return(ex.Message); } }
/// <summary> /// Write the specified collection of statistics to the XML /// statistics file, creating it if it does not already exist /// </summary> /// <param name="stats">The collection of statistics.</param> /// <param name="integrationResult">The build for which the /// statistics were collected.</param> /// <remarks> /// The XML document takes the following form: /// <statistics> /// <integration build-label="label" status="status" /// day="day_of_month" month="month_name" year="year"> /// <statistic name="name"> /// value /// </statistic> /// </integration> /// </statistics> /// </remarks> private static void UpdateXmlFile(IEnumerable <StatisticResult> stats, IIntegrationResult integrationResult) { Directory.CreateDirectory(integrationResult.ArtifactDirectory); // make an xml element of the current integration System.Text.StringBuilder integration = new System.Text.StringBuilder(); DateTime now = DateTime.Now; integration.AppendFormat("<integration build-label=\"{0}\" status=\"{1}\" day=\"{2}\" month=\"{3}\" year=\"{4}\">", integrationResult.Label, integrationResult.Status.ToString(), now.Day.ToString(CultureInfo.CurrentCulture), now.ToString("MMM", CultureInfo.InvariantCulture), now.Year.ToString(CultureInfo.CurrentCulture)); integration.AppendLine(ToXml(stats)); integration.Append("</integration>"); // append to the statistics file string lastFile = XmlStatisticsFile(integrationResult); System.IO.FileStream fs = new System.IO.FileStream(lastFile, System.IO.FileMode.Append); fs.Seek(0, System.IO.SeekOrigin.End); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); sw.WriteLine(integration.ToString()); sw.Flush(); fs.Flush(); sw.Close(); fs.Close(); }
private bool BarChart = true; // if false is tick chart protected override void OnStart() { var ticktype = MarketSeries.TimeFrame.ToString(); if (ticktype.Contains("Tick")) { BarChart = false; } fiName = DataDir + "\\" + Symbol.Code + "-" + ticktype + ".csv"; string csvhead = BarChart ? "date,open,high,low,close" : "date,ask,bid"; if (System.IO.File.Exists(fiName) == false) { System.IO.File.WriteAllText(fiName, csvhead); } // had to open file this way to prevent .net from locking it and preventing // access by other processes when using to download live ticks. fstream = File.Open(fiName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); // setup to append to end of file fstream.Seek(0, SeekOrigin.End); // write stream has to be created after seek due to .net wierdness // creating with 0 prevents buffering since we want tick data // to be available to consumers right away. fwriter = new System.IO.StreamWriter(fstream, System.Text.Encoding.UTF8, 1); fwriter.WriteLine(); // QUESTION: How to tell when in Backtest mode so we // can create the stream with a large buffer and turn off // auto flush to improve IO performance. fwriter.AutoFlush = true; // with autoflush true will autocleanup // since we can not close since we may run forever }
private void BtnUcitajSliku_Click_1(object sender, EventArgs e) { try { FileStream fs; OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (ofd.SafeFileName.Split('.')[1] == "jpg" || ofd.SafeFileName.Split('.')[1] == "png" || ofd.SafeFileName.Split('.')[1] == "jpeg") { format = ofd.SafeFileName.Split('.')[1]; fs = new System.IO.FileStream(ofd.FileName, FileMode.Open, FileAccess.Read); slika = Image.FromStream(fs); PbSlikaIgraca.Image = Image.FromStream(fs); int duzina = Convert.ToInt32(fs.Length); byte[] bajtovi = new byte[duzina]; fs.Seek(0, SeekOrigin.Begin); int bytesRead = fs.Read(bajtovi, 0, duzina); } else { MessageBox.Show("Nepodrzan tip podataka,slika moze biti u jpg ili png formatu."); return; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public async Task <string> CaptureAndSaveAsync() { try { var bytes = await CaptureAsync(); Java.IO.File picturesFolder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); var directory = $"{picturesFolder.AbsolutePath}/Screenshots"; if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } string filePath = System.IO.Path.Combine(directory, "Screnshot-" + date + ".png"); using (System.IO.FileStream SourceStream = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate)) { SourceStream.Seek(0, System.IO.SeekOrigin.End); await SourceStream.WriteAsync(bytes, 0, bytes.Length); } return(filePath); } catch (Exception ex) { return(ex.Message); } }
public void StreamMedia(string filePath) { // stream audio and video files with support for range requests SetStatus(206); Context.Response.AddHeader("Accept-Ranges", "bytes"); int read; byte[] buffer = new byte[4096]; using (Stream stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { Context.Response.ContentLength64 = stream.Length; using (BinaryWriter writer = new BinaryWriter(Context.Response.OutputStream)) { if (!String.IsNullOrEmpty(Context.Request.Headers["Range"])) { string[] range = Context.Request.Headers["Range"].Split(new char[] { '=', '-' }); int beginPos = int.Parse(range[1]); int endPos = int.Parse(range[1]); stream.Seek(beginPos, SeekOrigin.Begin); Context.Response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", beginPos, stream.Length - 1, stream.Length)); } while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { writer.Write(buffer, 0, buffer.Length); writer.Flush(); } } } }
public void SavePalExp(System.IO.FileStream fStream) { try { byte[] expTmp = System.BitConverter.GetBytes(exp); byte[] rankTmp = System.BitConverter.GetBytes(rank); fStream.Seek(exp_offset, SeekOrigin.Begin); fStream.Write(expTmp, 0, expTmp.Length); //exp fStream.Write(rankTmp, 0, rankTmp.Length); // exp rest Saveushort(fStream, now_rank_offset, this.now_rank); Saveushort(fStream, MaxHP_offset, this.maxHP); Saveushort(fStream, MaxMP_offset, this.maxMP); Saveushort(fStream, HP_offset, this.hp); Saveushort(fStream, MP_offset, this.mp); Saveushort(fStream, power_offset, this.power); Saveushort(fStream, wakan_offset, this.wakan); Saveushort(fStream, defence_offset, this.defence); Saveushort(fStream, speed_offset, this.speed); Saveushort(fStream, luck_offset, this.luck); } catch (Exception e) { System.Console.WriteLine("Exception in PalExp.SavePalExp(): " + e.Message); System.Windows.Forms.MessageBox.Show("Exception in PalExp.SavePalExp(): " + e.Message); } }
/// <summary> /// Initializes a file stream with the specified <paramref name="fileName"/>. /// If <paramref name="append"/> is FALSE, a new file is always created and an /// existing file is overridden.. Otherwise an existing file is extended. If /// no file exists, a new one is always created. /// </summary> public virtual void InitStream(string fileName, bool append) { FileMode fileMode = append ? FileMode.OpenOrCreate : FileMode.Create; _fileStream = OnInitStream(fileName, fileMode); _fileStream.Seek(0, SeekOrigin.End); }
private void button9_Click(object sender, EventArgs e) { FileStream stream; OpenFileDialog ofd = new OpenFileDialog(); var client = new MongoClient("mongodb://localhost"); var database = client.GetDatabase("docs"); var fs = new GridFSBucket(database); if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { stream = new System.IO.FileStream(ofd.FileName, FileMode.Open, FileAccess.Read); //SoundPlayer simpleSound = new SoundPlayer(stream); //simpleSound.Play(); var split = ofd.SafeFileName.Split('.'); if (split[1] != "mp3") { MessageBox.Show("Izaberite mp3 fajl!"); return; } GridFSUploadOptions opcije = new GridFSUploadOptions(); opcije.ContentType = "audio/mp3"; opcije.ChunkSizeBytes = Convert.ToInt32(stream.Length) / 4; int duzina = Convert.ToInt32(stream.Length); byte[] bajtovi = new byte[duzina]; stream.Seek(0, SeekOrigin.Begin); int bytesRead = stream.Read(bajtovi, 0, duzina); fs.UploadFromBytes(ofd.SafeFileName, bajtovi, opcije); } }
public SQLCEVersion DetermineVersion(string fileName) { var versionDictionary = new System.Collections.Generic.Dictionary <int, SQLCEVersion> { { 0x73616261, SQLCEVersion.SQLCE20 }, { 0x002dd714, SQLCEVersion.SQLCE30 }, { 0x00357b9d, SQLCEVersion.SQLCE35 }, { 0x00357dd9, SQLCEVersion.SQLCE35 }, { 0x003d0900, SQLCEVersion.SQLCE40 } }; int versionLongword; using (var fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)) { fs.Seek(16, System.IO.SeekOrigin.Begin); using (System.IO.BinaryReader reader = new System.IO.BinaryReader(fs)) { versionLongword = reader.ReadInt32(); } } if (versionDictionary.ContainsKey(versionLongword)) { return(versionDictionary[versionLongword]); } throw new ApplicationException("Unable to determine database file version"); }
/// <summary> /// 合并文件 /// </summary> /// <param name="chunk">文件分段信息</param> /// <returns>文件分段信息</returns> internal virtual ChunkInfo Merge(ChunkInfo chunk) { if (string.IsNullOrEmpty(chunk.ChunkUrl) || !io.File.Exists(chunk.ChunkUrl)) { throw new io.FileNotFoundException("没有找到文件分段!"); } using (var fileStream = new io.FileStream(chunk.CacheFileFullName = io.Path.Combine(_url, chunk.FileID), io.FileMode.OpenOrCreate)) using (var stream = chunk.ChunkStream ?? io.File.OpenRead(chunk.ChunkUrl)) { if (chunk.Chunk.HasValue) { fileStream.Seek((chunk.ChunkSize * (chunk.Chunk ?? 0)), io.SeekOrigin.Begin); } int readLen = 0; var buffer = new byte[8 * 1024]; while ((readLen = stream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, readLen); fileStream.Flush(); } return(chunk); } }
public string Read(string filePath) { if (!System.IO.File.Exists(filePath)) { throw new Exception("文件不存在"); } StringBuilder result = new StringBuilder(); using (System.IO.FileStream file = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous)) { byte[] buffer = new byte[file.Length]; file.Seek(0, System.IO.SeekOrigin.Begin); file.Read(buffer, 0, buffer.Length); System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream.Write(buffer, 0, buffer.Length); var content = System.Text.Encoding.UTF8.GetString(stream.ToArray()); result.Append(content); stream.Flush(); stream.Dispose(); stream.Close(); file.Flush(); file.Close(); } return(result.ToString()); }
//End FUNCTION Write_To_CSV_File ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //// CREATE CSV FILE /////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protected void Create_CSV_File() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; //Server Time Recod string str_temp1 = string.Format("{0:ddd-d-MMM-y}", Server.Time); //Desktop Folder PATH and NAME str_DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); str_FolderPath = Path.Combine(str_DesktopFolder, p_str_Folder_Name); //Create Directory and make the file name Directory.CreateDirectory(str_FolderPath); str_FileName = Path.Combine(str_FolderPath, Symbol.Code + " " + TimeFrame + " " + str_temp1 + ".csv"); //Print("File Path : " + str_FilePath); //Create or OVER RIDE Existing FILE and then Close it which is a must. File_Stream = File.Create(str_FileName); File_Stream.Close(); //Open File to prevent .NET from locking it and preventing access by other processes File_Stream = File.Open(str_FileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); //Seek End of File to write File_Stream.Seek(0, SeekOrigin.End); //File Writer Stream to be created. File_Writer = new System.IO.StreamWriter(File_Stream, System.Text.Encoding.UTF8, 1); //Auto Flush to improve IO performance File_Writer.AutoFlush = true; }
/* * Adds file to user entry in order to allow sharing */ public void shareFile(string username, string filename) { try { textDbMut.WaitOne(); System.IO.FileStream fileStream = new System.IO.FileStream(pathDb, FileMode.Open, FileAccess.ReadWrite, FileShare.None); System.IO.StreamReader iStream = new System.IO.StreamReader(fileStream); System.IO.StreamWriter oStream = new System.IO.StreamWriter(fileStream); string line; char[] deliminator = " | ".ToCharArray(); while ((line = iStream.ReadLine()) != null) { string[] attributes = line.Split(deliminator); if (username == attributes[0]) { fileStream.Seek(-1, SeekOrigin.Current); oStream.WriteLine(" | " + filename); oStream.Flush(); printLogger("File sharing entry added"); break; } } fileStream.Close(); textDbMut.ReleaseMutex(); } catch (Exception exc) { MessageBox.Show("Exception thrown at file reading: " + exc.Message); textDbMut.ReleaseMutex(); return; } }
public Archive(string fileName) { FileName = fileName; using (System.IO.FileStream stream = System.IO.File.Open(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { CFHEADER header = CFHEADER.FromStream(stream); int dataBlocks = 0; for (int i = 0; i < header.CFHEADER_FIXED.cFolders; i++) { CFFOLDER folder = CFFOLDER.FromStream(stream, header); m_folders.Add(folder); dataBlocks += folder.cCFData; } stream.Seek(header.CFHEADER_FIXED.coffFiles, System.IO.SeekOrigin.Begin); for (int i = 0; i < header.CFHEADER_FIXED.cFiles; i++) { CFFILE file = CFFILE.FromStream(stream); m_files.Add(file); } stream.Close(); } }
public static void WriteFileLog(string strLog) { //if (!Constant.IsDebug) // return; try { string pathd = System.IO.Directory.GetCurrentDirectory(); //当前程序路径 pathd += "\\log"; if (!Directory.Exists(pathd)) { Directory.CreateDirectory(pathd); } string FileName = pathd + "\\" + DateTime.Now.ToString("yy_MM_dd_") + Constant.LogFileName; string TimeStr = "记录时间:" + DateTime.Now.ToString("HH:mm:ss.fff") + "\r\n"; byte[] b = System.Text.Encoding.GetEncoding(936).GetBytes(TimeStr + strLog); System.IO.FileStream f1 = System.IO.File.Open(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); f1.Seek(0, SeekOrigin.End); f1.Write(b, 0, b.Length); f1.Close(); } catch { } }
public void initializationMyCountK2() { byte[] byteArray = new byte[32]; myCountK2.O1 = 0; myCountK2.O2 = 0; myCountK2.T1 = 0; myCountK2.T2 = 0; myCountK2.O31 = 0; myCountK2.O32 = 0; myCountK2.T31 = 0; myCountK2.T32 = 0; BitConverter.GetBytes(myCountK2.O1).CopyTo(byteArray, 0); BitConverter.GetBytes(myCountK2.O2).CopyTo(byteArray, 4); BitConverter.GetBytes(myCountK2.T1).CopyTo(byteArray, 8); BitConverter.GetBytes(myCountK2.T2).CopyTo(byteArray, 12); BitConverter.GetBytes(myCountK2.O31).CopyTo(byteArray, 16); BitConverter.GetBytes(myCountK2.O32).CopyTo(byteArray, 20); BitConverter.GetBytes(myCountK2.T31).CopyTo(byteArray, 24); BitConverter.GetBytes(myCountK2.T32).CopyTo(byteArray, 28); using (var stream = new System.IO.FileStream("Z:\\Belaz\\MycountK2.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))//запись в файл { //Перемещаемся в файле на 100 байт от начала stream.Seek(0, System.IO.SeekOrigin.Begin); //Записываем буфер stream.Write(byteArray, 0, byteArray.Length); } }
protected override void OnStart() { var ticktype = MarketSeries.TimeFrame.ToString(); fiName = DataDir + "\\" + "exp-" + Symbol.Code + "-ticks.csv"; Print("fiName=" + fiName); if (System.IO.File.Exists(fiName) == false) { // generate new file with CSV header only if // one does not already exist. System.IO.File.WriteAllText(fiName, csvhead); } // had to open file this way to prevent .net from locking it and preventing // access by other processes when using to download live ticks. fstream = File.Open(fiName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); // setup to append to end of file Print("File is Open"); fstream.Seek(0, SeekOrigin.End); // write stream has to be created after seek due to .net wierdness // creating with 0 prevents buffering since we want tick data // to be available to consumers right away. fwriter = new System.IO.StreamWriter(fstream, System.Text.Encoding.UTF8, 1); // QUESTION: How to tell when in Backtest mode so we // can create the stream with a large buffer and turn off // auto flush to improve IO performance. Print("Fwriter is created"); fwriter.AutoFlush = true; // with autoflush true will autocleanup // since we can not close since we may run forever Print("done onStart()"); }
private void OnOnReqFileInfoBackWrInThrd(object obj) { Tuple <string, RquFileInfoBack> tmp = null; while (queue.TryDequeue(out tmp)) { if (tmp == null) { continue; } if (_data.ContainsKey(tmp.Item1) == false) { continue; } using (System.IO.FileStream stream = System.IO.File.OpenWrite(tmp.Item1)) { stream.Seek(tmp.Item2.CurrentPackageIndex * tmp.Item2.PackageLength, System.IO.SeekOrigin.Begin); var buf = System.Convert.FromBase64String(tmp.Item2.Data); stream.Write(buf, 0, buf.Length); stream.Flush(); } } if (queue.Count == 0 && _data.Count > 0) { var ntr = (from t in _data where t.Value.Count > 0 && t.Value[0].Item1 == t.Value.Count select t.Key).ToList(); foreach (var f in ntr) { _data[f].Clear(); List <Tuple <int, int> > tmpr = null; _data.TryRemove(f, out tmpr); } } }
static void WriteToFile(CallMethodLogInformation log) { #if (NET35) string path = CombinePath(AutoLogger.ApplicationDirectory, "Logs", log.DateTime.Year.ToString(), log.DateTime.Month.ToString(), log.DateTime.Day.ToString()); #else string path = System.IO.Path.Combine(AutoLogger.ApplicationDirectory, "Logs", log.DateTime.Year.ToString(), log.DateTime.Month.ToString(), log.DateTime.Day.ToString()); #endif if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } path = System.IO.Path.Combine(path, $"{log.DateTime.Year}-{log.DateTime.Month}-{log.DateTime.Day} {log.DateTime.ToLocalTime().Hour}.log"); StringBuilder build = new StringBuilder(); build.AppendLine("########################################"); build.AppendLine("Client Information:"); build.AppendLine($" Ip Address: {log.IPAddress}"); build.AppendLine($" SessionId: {log.SessionId}"); build.AppendLine($" Connected Time: {GetDateTimeString(log.ConnectedDateTime)}"); build.AppendLine(""); build.AppendLine($"Call Information:"); build.AppendLine($" Service Name: {log.ServiceName}"); build.Append($" Method: {log.Method.Name}("); bool isFirst = true; foreach (var parameter in log.Method.GetParameters()) { build.Append((isFirst ? "" : ",") + parameter.ParameterType.Name + " " + parameter.Name); isFirst = false; } build.AppendLine(")"); build.AppendLine($" With Values:"); foreach (var parameter in log.Parameters) { build.AppendLine(" "+ (parameter.Value == null ? "Null" : JsonConvert.SerializeObject(parameter.Value, Formatting.None, new JsonSerializerSettings() { Formatting = Formatting.None }).Replace(@"\""", ""))); } build.AppendLine(""); build.AppendLine($"Result Information:"); build.AppendLine(" "+ (log.Result == null ? "Null" : JsonConvert.SerializeObject(log.Result, Formatting.None, new JsonSerializerSettings() { Formatting = Formatting.None })).Replace(@"\""", "")); build.AppendLine(""); build.AppendLine($"Invoked Time:"); build.AppendLine($" {GetDateTimeString(log.DateTime)}"); build.AppendLine($"Result Time:"); build.AppendLine($" {GetDateTimeString(log.ResultDateTime)}"); build.AppendLine("----------------------------------------------------------------------------------------"); build.AppendLine(""); using (var stream = new System.IO.FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { stream.Seek(0, System.IO.SeekOrigin.End); byte[] bytes = Encoding.UTF8.GetBytes(build.ToString()); stream.Write(bytes, 0, bytes.Length); } }
private static void FileWrite(string path, int index, long packageSize, int receiveSize, byte[] data) { using (System.IO.FileStream stream = System.IO.File.OpenWrite(path)) { stream.Seek((long)index * (long)packageSize, System.IO.SeekOrigin.Begin); stream.Write(data, 0, receiveSize); stream.Flush(); } }