public static void DecryptFile(string strKey, string pathCypheredTextFile, string pathPlainTextFile) { // Place la clé de déchiffrement dans un tableau d'octets byte[] key = GenerateAlgotihmInputs(strKey); // Place le vecteur d'initialisation dans un tableau d'octets byte[] iv = GenerateAlgotihmInputs(strKey); // Filestream of the new file that will be decrypted. Directory.CreateDirectory(Directory.GetParent(pathPlainTextFile).FullName); FileStream fsCrypt = new FileStream(pathPlainTextFile, FileMode.Create); RijndaelManaged rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; rijndael.Key = key; rijndael.IV = iv; ICryptoTransform aesDecryptor = rijndael.CreateDecryptor(); CryptoStream cs = new CryptoStream(fsCrypt, aesDecryptor, CryptoStreamMode.Write); // FileStream of the file that is currently encrypted. FileStream fsIn = new FileStream(pathCypheredTextFile, FileMode.OpenOrCreate); int data; while ((data = fsIn.ReadByte()) != -1) cs.WriteByte((byte)data); cs.Close(); fsIn.Close(); fsCrypt.Close(); }
public static StreamReader OpenStream(FileStream fs, Encoding suggestedEncoding, Encoding defaultEncoding) { if (fs.Length > 3) { // the autodetection of StreamReader is not capable of detecting the difference // between ISO-8859-1 and UTF-8 without BOM. int firstByte = fs.ReadByte(); int secondByte = fs.ReadByte(); switch ((firstByte << 8) | secondByte) { case 0x0000: // either UTF-32 Big Endian or a binary file; use StreamReader case 0xfffe: // Unicode BOM (UTF-16 LE or UTF-32 LE) case 0xfeff: // UTF-16 BE BOM case 0xefbb: // start of UTF-8 BOM // StreamReader autodetection works fs.Position = 0; return new StreamReader(fs); default: return AutoDetect(fs, (byte)firstByte, (byte)secondByte, defaultEncoding); } } else { if (suggestedEncoding != null) { return new StreamReader(fs, suggestedEncoding); } else { return new StreamReader(fs); } } }
static void Main(string[] args) { FileStream infile, outfile; int tam; char x; infile = new System.IO.FileStream("teste.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); outfile = new System.IO.FileStream("teste2.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); tam = (int)infile.Length; for (int i = 0; i < tam; ++i) { x = (char)infile.ReadByte(); if (x == '#') { ++i; do { x = (char)infile.ReadByte(); ++i; }while (x != '#'); } else if (x != ' ') { outfile.WriteByte((byte)char.ToUpper(x)); } } infile.Close(); outfile.Close(); }
/// <summary> /// 导出文本 /// </summary> public void ExtractText() { string exportedFile = ExportGBNB(true); if (exportedFile.Equals(string.Empty)) { Console.WriteLine("文件:{0}不包含文本", fileToProc.FullName); return; } List<string> text = new List<string>(); using (FileStream reader = new FileStream(exportedFile, FileMode.Open, FileAccess.Read)) { GBNB gbnb = GetGBNBInfo(reader); reader.Seek(gbnb.TextOffset, SeekOrigin.Begin); for (int i = 0; i < gbnb.SentenceCount; i++) { List<byte> textData = new List<byte>(); byte singleData = (byte)reader.ReadByte(); while (singleData != 0) { textData.Add(singleData); singleData = (byte)reader.ReadByte(); } text.Add(Encoding.GetEncoding(932).GetString(textData.ToArray())); } WriteAllText(text, exportedFile + ".xml"); //File.WriteAllLines(exportedFile + ".txt", text.ToArray(), Encoding.UTF8); } }
public static void Init(string DofusPath) { mDofusPath = DofusPath; foreach (string File in Directory.GetFiles(mDofusPath + "\\app\\content\\gfx\\items\\")) { if (File.Contains("bitmap")) { mystream = new FileStream(File, FileMode.Open, FileAccess.Read); byte num = Convert.ToByte(mystream.ReadByte() + mystream.ReadByte()); if (num == 3) { mystream.Position = mystream.Length - 0x18L; int num2 = Convert.ToInt32(readUInt()); readUInt(); int num3 = Convert.ToInt32(readUInt()); int num4 = Convert.ToInt32(readUInt()); int num1 = Convert.ToInt32(readUInt()); int num10 = Convert.ToInt32(readUInt()); mystream.Position = num3; int num5 = num4; for (int i = 1; i <= num5; i++) { string key = readString(); int num7 = (int)(readUInt() + num2); int num8 = (int)(readUInt()); DictionnaryItemGFX.Add(key, new int[] { num7, num8 }); } mystream.Close(); } } } }
public static void filtro() { FileStream infile, outfile; int tam; char x; infile = new System.IO.FileStream(ProgramaFonte.getPathNome(), System.IO.FileMode.Open, System.IO.FileAccess.Read); outfile = new System.IO.FileStream("pftmp.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); tam = (int)infile.Length; for (int i = 0; i < tam; ++i) { x = (char)infile.ReadByte(); if (x == '#') { ++i; do { x = (char)infile.ReadByte(); ++i; }while (x != '#'); } else if (x != ' ') { outfile.WriteByte((byte)char.ToUpper(x)); } } infile.Close(); outfile.Close(); }
public static void main() { FileStream infile, outfile; int tam, dig = 0, let = 0, outr = 0; char x, y; infile = new System.IO.FileStream("teste-20140217.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); outfile = new System.IO.FileStream("teste2-20140217.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write); tam = (int)infile.Length; for (int i = 0; i < tam; ++i) { x = (char)infile.ReadByte(); if (x == ' ') continue; else if (x == '#') { do { i++; y = (char)infile.ReadByte(); } while (y != '#'); } else { outfile.WriteByte((byte)x); } } outfile.Close(); }
public static Ship Load(System.IO.FileStream fs, Dock d) { byte slevel = (byte)fs.ReadByte(); ShipType stype = (ShipType)fs.ReadByte(); Ship s = PoolMaster.current.GetShip(slevel, stype); s.level = slevel; s.type = stype; s.destination = d; s.docked = fs.ReadByte() == 1; var data = new byte[34]; fs.Read(data, 0, data.Length); s.transform.position = new Vector3( System.BitConverter.ToSingle(data, 0), System.BitConverter.ToSingle(data, 4), System.BitConverter.ToSingle(data, 8) ); s.transform.rotation = new Quaternion( System.BitConverter.ToSingle(data, 12), System.BitConverter.ToSingle(data, 16), System.BitConverter.ToSingle(data, 20), System.BitConverter.ToSingle(data, 24) ); s.speed = System.BitConverter.ToSingle(data, 28); s.unloaded = data[32] == 1; s.xAxisMoving = data[33] == 1; return(s); }
/// <summary> /// Reads bytes from FileStream, decodes them, and then returns them /// </summary> /// <param name="r">FileStream to read from</param> /// <returns>Unencoded ride bytes</returns> public static byte[] Read(FileStream r) { List<byte> decodedBytes = new List<byte>(); while (r.Position < r.Length - 4) // - 4 to strip checksum { int b = r.ReadByte(); if (b >= 0 && b <= 128) { // pos, read next b bytes for (int i = 0; i <= b; i++) { decodedBytes.Add((byte)r.ReadByte()); } } else { // neg, repeat next byte (1 - b) times byte repeatByte = (byte)r.ReadByte(); int repeatTimes = (byte)(1 - b); for (int i = 0; i < repeatTimes; i++) { decodedBytes.Add(repeatByte); } } } return decodedBytes.ToArray(); }
public string Read(string valueName) { try { using (FileStream f = new FileStream(MakePath(valueName), FileMode.Open)) { if (f.ReadByte() != 0) return null; var b = f.ReadByte(); if (b < 0) return null; byte csum = (byte)b; MemoryStream ms = new MemoryStream(); while (true) { b = f.ReadByte(); if (b < 0) { if (csum == 0) return Encoding.UTF8.GetString(ms.ToArray()); return null; } ms.WriteByte((byte)b); csum -= (byte)b; } } } catch(IOException) { return null; } }
public uint calculateF2Checksum(string a_fileName, int start, int length) { FileStream fs = new FileStream(a_fileName, FileMode.Open, FileAccess.Read); uint[] xorTable = new uint[8] { 0x81184224, 0x24421881, 0xc33c6666, 0x3cc3c3c3, 0x11882244, 0x18241824, 0x84211248, 0x12345678 }; byte[] data = new byte[4]; byte xorCount; uint temp = 0; uint checksum = 0; uint count = 0; fs.Position = start; checksum = 0; count = 0; xorCount = 1; while( count < length && fs.Position < 0x7FFFF ) { data[0] = (byte)fs.ReadByte(); data[1] = (byte)fs.ReadByte(); data[2] = (byte)fs.ReadByte(); data[3] = (byte)fs.ReadByte(); temp = (uint)(data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]); checksum += temp ^ xorTable[xorCount++]; if( xorCount > 7 ) xorCount = 0; count += 4; } checksum ^= 0x40314081; checksum -= 0x7FEFDFD0; fs.Close(); return checksum; }
/* INPUT 1: ../../Faded.mp4 ../../ 5 INPUT 2: ../../text.txt ../../ 3 * * * */ private static void Slice(string sourceFile, string destinationDirectory, int parts) { FileStream reader = new FileStream(sourceFile, FileMode.Open); FileInfo file = new FileInfo(sourceFile); long chunkSize = (long)(file.Length/parts); BigInteger counter = -1; if (file.Length%2 == 1) { counter = 0; } int fileCounter = 1; int readBytesVariable = reader.ReadByte(); List<byte> lsBytes = new List<byte>(); lsBytes.Add((byte)readBytesVariable); while (readBytesVariable != -1) { if ((counter%chunkSize == 0 && counter != 0) || counter == file.Length) { string fileName = destinationDirectory + "Part-" + fileCounter + "." + sourceFile.Split(new char[]{'.'},StringSplitOptions.RemoveEmptyEntries).LastOrDefault(); FileStream writer = new FileStream(fileName, FileMode.Create,FileAccess.Write); writer.Write(lsBytes.ToArray(), 0,lsBytes.Count); writer.Flush(); writer.Dispose(); lsBytes.Clear(); fileCounter++; } readBytesVariable = reader.ReadByte(); lsBytes.Add((byte)readBytesVariable); counter++; } }
public static void main() { FileStream infile, outfile; int tam, dig = 0, let = 0, outr = 0; char x, y; List<String> a = new List<String>(); infile = new System.IO.FileStream("teste-20140224.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); tam = (int)infile.Length; for (int i = 0; i < tam; ++i) { x = (char)infile.ReadByte(); if (char.IsNumber(x)) { String valor = ""; do { valor += x; i++; x = (char)infile.ReadByte(); } while (char.IsNumber(x)); Console.WriteLine(valor); } } Console.ReadKey(); }
public PE(string fileName) { FileName = Path.GetFullPath(fileName); Uri = new Uri(FileName); IsPEFile = false; try { _fs = File.OpenRead(FileName); byte byteRead = (byte)_fs.ReadByte(); if (byteRead != 'M') { return; } byteRead = (byte)_fs.ReadByte(); if (byteRead != 'Z') { return; } _fs.Seek(0, SeekOrigin.Begin); _peReader = new PEReader(_fs); PEHeaders = _peReader.PEHeaders; IsPEFile = true; } catch (IOException e) { LoadException = e; } catch (BadImageFormatException e) { LoadException = e; } catch (UnauthorizedAccessException e) { LoadException = e; } if (IsPEFile) { m_pImage = new SafePointer(_peReader.GetEntireImage().GetContent().ToBuilder().ToArray()); if (IsManaged) { _metadataReader = _peReader.GetMetadataReader(); } } }
/// <summary> /// This function enabels you to hide a message insider a BMP /// </summary> /// <param name="inputPath">input BMP path</param> /// <param name="outputPath">output BMP path</param> /// <param name="message">message to hide</param> public void HideMessage(string inputPath,string outputPath,string message) { int readByte; int count=14; BMP bitmap=new BMP(inputPath); bitmap.BitmapFileHeader.bfOffBits+=(message.Length+1); bitmap.BitmapFileHeader.bfSize+=(message.Length+1); FileStream br=new FileStream(inputPath,FileMode.Open); BinaryWriter bw=new BinaryWriter(File.OpenWrite(outputPath)); bitmap.WriteBMPFileHeader(bw); br.Seek(14,SeekOrigin.Begin); while(count<(bitmap.BitmapFileHeader.bfOffBits-(message.Length+1))) { bw.Write((byte)br.ReadByte()); count++; } for(int i=0;i<message.Length;i++) { bw.Write(message[i]); } bw.Write(Convert.ToByte(message.Length)); while((readByte=br.ReadByte())>=0) { bw.Write((byte)readByte); } bw.Close(); br.Close(); }
static void SampleReadWrite(string filePath) { using (Stream s = new System.IO.FileStream(filePath, FileMode.Create)) { Console.WriteLine(s.CanRead); // True Console.WriteLine(s.CanWrite); // True Console.WriteLine(s.CanSeek); //True (возможность поиска в потоке) s.WriteByte(101); //запись байта s.WriteByte(102); byte[] block = { 1, 2, 3, 4, 5 }; s.Write(block, 0, block.Length); // Записать блок из 5 байтов Console.WriteLine(s.Length); // 7 Console.WriteLine(s.Position); // 7 s.Position = 0; // Переместиться обратно в начало Console.WriteLine(s.ReadByte()); // 101 Console.WriteLine(s.ReadByte()); // 102 // Читать из потока в массив block: Console.WriteLine(s.Read(block, 0, block.Length)); // 5 //Предполагая, что последний вызов Read возвратил 5, //мы находимся в конце файла, и Read теперь возвратит 0: Console.WriteLine(s.Read(block, 0, block.Length)); // 0 } }
static void Main(string[] args) { FileStream infile; int tam; char x; infile = new System.IO.FileStream("Teste.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read); tam = (int)infile.Length; for (int i = 0; i < tam; ++i) { x = (char)infile.ReadByte(); if (char.IsDigit(x)) { do { Console.Write(x); x = (char)infile.ReadByte(); } while ((char.IsDigit(x))); Console.WriteLine(); } } Console.ReadKey(); }
private void Load(System.IO.FileStream fs) { int resCount = fs.ReadByte(); isForSale = new bool?[resCount]; minValueForTrading = new int[resCount]; int x; var data = new byte[4]; for (int i = 0; i < resCount; i++) { x = fs.ReadByte(); if (x == 2) { isForSale[i] = null; minValueForTrading[i] = 0; } else { isForSale[i] = x == 1 ? true : false; fs.Read(data, 0, 4); minValueForTrading[i] = System.BitConverter.ToInt32(data, 0); } } // data = new byte[13]; fs.Read(data, 0, data.Length); immigrationEnabled = data[0] == 1; immigrationPlan = System.BitConverter.ToInt32(data, 1); immigrantsArrived = System.BitConverter.ToUInt32(data, 5); emigrantsGone = System.BitConverter.ToUInt32(data, 9); }
public void LoadChunkData(System.IO.FileStream fs) { if (blocks != null) { ClearChunk(); } chunkSize = (byte)fs.ReadByte(); Prepare(); var data = new byte[4]; fs.Read(data, 0, 4); surfaces = null; int blocksCount = System.BitConverter.ToInt32(data, 0); if (blocksCount > 1000000) { Debug.Log("chunk load error - too much blocks"); GameMaster.LoadingFail(); return; } else { blocks = new Dictionary <ChunkPos, Block>(); Block b; for (int i = 0; i < blocksCount; i++) { b = Block.Load(fs, this); if (b != null) { blocks.Add(b.pos, b); } } } PreparePlanes(); RecalculateSurfacesList(); // var rb = fs.ReadByte(); if (rb == 1) { if (nature == null) { nature = GetNature(); } nature.Load(fs, this); } if (borderDrawn) { DrawBorder(); } RenderDataFullRecalculation(); FollowingCamera.main.WeNeedUpdate(); }
public static Block Load(System.IO.FileStream fs, Chunk c) { var b = new Block(c, new ChunkPos(fs.ReadByte(), fs.ReadByte(), fs.ReadByte())); if (fs.ReadByte() == 1) { b.extension = BlockExtension.Load(fs, b); } return(b); }
public static int Execute( List<string> args ) { if ( args.Count == 0 ) { Console.WriteLine( "This is intended to help extracting skit audio from the Xbox 360 game files." ); Console.WriteLine( "Do the following in order:" ); Console.WriteLine( "-- unpack chat.svo (FPS4 archive, with HyoutaTools -> ToVfps4e)" ); Console.WriteLine( "-- decompress individual skit with xbdecompress" ); Console.WriteLine( "-- unpack skit (FPS4 archive, with HyoutaTools -> ToVfps4e)" ); Console.WriteLine( "-- cut SE3 header from audio file to get a nub archive" ); Console.WriteLine( " (file 0004, seems to be 0x800 bytes for skits but can be bigger, first four bytes of new file should be 0x00020100)" ); Console.WriteLine( "-- extract nub archive with NUBExt r12beta" ); Console.WriteLine( "-- this gives you an \"xma\" file that isn't actually an xma, run this tool on it" ); Console.WriteLine( "-- resulting file is a valid enough xma file that can be converted to WAV with \"toWav\"" ); return -1; } string filename = args[0]; using ( var source = new FileStream( filename, FileMode.Open ) ) { using ( var dest = new FileStream( filename + "-real.xma", FileMode.Create ) ) { source.Position = 0x100; int dataLength = (int)( source.Length - source.Position ); dest.WriteAscii( "RIFF" ); dest.WriteUInt32( (uint)dataLength + 0x34 ); dest.WriteAscii( "WAVE" ); dest.WriteAscii( "fmt " ); dest.WriteUInt32( 0x20 ); source.Position = 0xBC; dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteByte( (byte)source.ReadByte() ); dest.WriteByte( (byte)source.ReadByte() ); dest.WriteUInt32( source.ReadUInt32().SwapEndian() ); dest.WriteUInt32( source.ReadUInt32().SwapEndian() ); dest.WriteUInt32( source.ReadUInt32().SwapEndian() ); dest.WriteUInt32( source.ReadUInt32().SwapEndian() ); dest.WriteByte( (byte)source.ReadByte() ); dest.WriteByte( (byte)source.ReadByte() ); dest.WriteUInt16( source.ReadUInt16().SwapEndian() ); dest.WriteAscii( "data" ); dest.WriteUInt32( (uint)dataLength ); source.Position = 0x100; Util.CopyStream( source, dest, dataLength ); } } return 0; }
public void WriteOnlyThrows() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write)) { Assert.Throws<NotSupportedException>(() => fs.ReadByte()); fs.Dispose(); // Disposed checking happens first Assert.Throws<ObjectDisposedException>(() => fs.ReadByte()); } }
/// <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; }
public static string[] ReadAllLines(string path) { List<string> plain = new List<string>(); string plainBuf = ""; FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read); if (stream.ReadByte() == 0) { //Encrypted RC4Encryption enc = new RC4Encryption(Config.I.FilePassword); int read = 0; while (read != -1 && stream.Position < stream.Length) { read = stream.ReadByte(); char p = (char)(read ^ enc.NextByte()); if (p == "\n".ToCharArray()[0]) { if (plainBuf.EndsWith("\r")) plainBuf.Remove(plainBuf.LastIndexOf("\r")); if (!string.IsNullOrEmpty(plainBuf)) plain.Add(plainBuf); plainBuf = ""; } else plainBuf += p; } } else { //Plain stream.Seek(0, SeekOrigin.Begin); int read = 0; while (read != -1 && stream.Position < stream.Length) { read = stream.ReadByte(); char p = (char)(read); if (p == "\n".ToCharArray()[0]) { if (plainBuf.EndsWith("\r")) plainBuf.Remove(plainBuf.LastIndexOf("\r")); if (!string.IsNullOrEmpty(plainBuf)) plain.Add(plainBuf); plainBuf = ""; } else plainBuf += p; } } stream.Close(); if (!string.IsNullOrEmpty(plainBuf)) plain.Add(plainBuf); return plain.ToArray(); }
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; }
public static string ReadString(FileStream fs) { string s = ""; byte[] buff = new byte[4]; for (int i = 0; i < 4; i++) buff[i] = (byte)fs.ReadByte(); int count = BitConverter.ToInt32(buff, 0); buff = new byte[count]; for (int i = 0; i < count; i++) buff[i] = (byte)fs.ReadByte(); s = GetString(buff); return s; }
public static void run(string filename) { var stack = new Stack<uint>(); var reg = new uint[] { 0, 0, 0, 0, 0, 0, 0, 0 }; uint pc = 0, op, a, b, c, m; var d = 0; var mem = new Dictionary<uint, uint[]>(); // load memory using (var fs = new FileStream(filename, FileMode.Open)) { var v = new List<uint>(); while ((d = fs.ReadByte()) != -1) { for (int i = 0; i < 3; i++) d = (d << 8) + fs.ReadByte(); v.Add((uint)d); } mem.Add(0, v.ToArray()); } // spin while (true) { m = mem[0][pc++]; op = (m >> 28) & 0xF; c = m & 0x7; b = (m >> 3) & 0x7; a = (m >> 6) & 0x7; if (stack.Count == 0) stack.Push((uint)mem.Count); switch (op) { case 0: if (reg[c] != 0) reg[a] = reg[b]; break; case 1: reg[a] = mem[reg[b]][reg[c]]; break; case 2: mem[reg[a]][reg[b]] = reg[c]; break; case 3: reg[a] = reg[b] + reg[c]; break; case 4: reg[a] = reg[b] * reg[c]; break; case 5: reg[a] = reg[b] / reg[c]; break; case 6: reg[a] = ~(reg[b] & reg[c]); break; case 7: return; case 8: uint s = reg[c]; mem.Add(reg[b] = stack.Pop(), new uint[s]); break; case 9: mem.Remove(reg[c]); stack.Push(reg[c]); break; case 10: Console.Write((char)reg[c]); break; case 11: reg[c] = (uint)Console.Read(); break; case 12: pc = reg[c]; if (reg[b] != 0) mem[0] = (uint[])mem[reg[b]].Clone(); break; case 13: reg[(m >> 25) & 0x7] = m & 0x1FFFFFF; break; default: Console.WriteLine("\nGuru Meditation"); return; } } }
public void ProcessFile(FileInfo file) { _variables.Clear(); _todo.Clear(); if (_addMissing) { foreach (var item in _args) _todo.Add(item.Name, item.Value); } var projFiles = new List<FileInfo>(file.Directory.GetFiles("*.csproj")); if (file.Directory.Parent != null) projFiles.AddRange(file.Directory.Parent.GetFiles("*.csproj")); if (projFiles.Count > 0) ReadProjectValues(projFiles[0]); bool detect; using (var io = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { int first = io.ReadByte(); detect = first == 0 || first == 239 || first == 254 || first == 255 || (first == 43 && io.ReadByte() == 47 && io.ReadByte() == 118); } string text; Encoding encoding; using (var rdr = detect ? new StreamReader(file.FullName, true) : new StreamReader(file.FullName, Encoding.GetEncoding(CultureInfo.InstalledUICulture.TextInfo.OEMCodePage))) { encoding = rdr.CurrentEncoding; text = rdr.ReadToEnd(); } string modified = _pattern.Replace(text, ReplaceValue); if (_todo.Count > 0) { string newText = AddMisingAttributes(modified.EndsWith(Environment.NewLine) ? modified.EndsWith(Environment.NewLine + Environment.NewLine) ? 0 : 1 : 2); modified += _pattern.Replace(newText, ReplaceValue); } if (text != modified) { if ((file.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) file.Attributes = file.Attributes & ~FileAttributes.ReadOnly; using (var wtr = new StreamWriter(file.FullName, false, encoding)) wtr.Write(modified); } }
/// <summary> /// Initializes a new instance of CFramePack from a valid FileStream. /// </summary> /// <param name="file">The FileStream as it would be read by DarkEden.</param> public CCreatureFramePack(ref FileStream file) { if (file.Length == 0) return; this.Creatures = new List<Creature>(); byte[] _crc = new byte[2]; file.Read(_crc, 0, 2); UInt16 creaturecount = BitConverter.ToUInt16(_crc, 0); for (int i = 0; i < creaturecount; i++) { Creature cr; byte actioncount = (byte)file.ReadByte(); cr.Actions = new List<Action>(); for (int a = 0; a < actioncount; a++) { Action ac; byte dircount = (byte)file.ReadByte(); ac.Directions = new List<Direction>(); for (int d = 0; d < dircount; d++ ) { Direction di; byte[] _frc = new byte[2]; file.Read(_frc, 0, 2); UInt16 framecount = BitConverter.ToUInt16(_frc, 0); di.Frames = new CCreatureFrame[framecount]; for (int f = 0; f < framecount; f++) { di.Frames[f] = new CCreatureFrame(ref file); } ac.Directions.Add(di); } cr.Actions.Add(ac); } this.Creatures.Add(cr); } }
/// <summary> /// generates varbinary string from assembly file /// </summary> /// <param name="assemblyPath"> </param> /// <returns> </returns> public static string GetAssemblyBits(string assemblyPath) { var builder = new StringBuilder(); builder.Append("0x"); using (var stream = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { var currentByte = stream.ReadByte(); while (currentByte > -1) { builder.Append(currentByte.ToString("X2", CultureInfo.InvariantCulture)); currentByte = stream.ReadByte(); } } return builder.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="Paint.CanvasPlayback"/> class. /// </summary> /// <param name='filename'>Name of the file containing all the playback commands</param> public CanvasPlayback(string filename) { this.fileStream = File.OpenRead(filename); this.playbackCommandTotal = fileStream.ReadByte() | (fileStream.ReadByte()) << 8 | (fileStream.ReadByte()) << 16 | (fileStream.ReadByte()) << 24; // skip past the final brush size and color as we don't need to know them fileStream.Seek(8, SeekOrigin.Current); this.Color = Color.White; }
public void LoadPlanesData(System.IO.FileStream fs) { var b = fs.ReadByte(); IPlanableSupportClass.AddBlockRepresentation(this, basement, ref myBlock, false); if (b == 1) { upperPlane = Plane.Load(fs, this); } b = fs.ReadByte(); if (b == 1) { bottomPlane = Plane.Load(fs, this); } }
// Methods private bool findByteSequence(byte[] sequence, byte[] seq_mask) { int index = 0; int length = sequence.Length; FileStream stream = null; try { stream = new FileStream(this.m_fileName, FileMode.Open, FileAccess.Read); while (stream.Position < this.m_fileLength) { byte num = (byte)stream.ReadByte(); if ((num == sequence[index]) || (seq_mask[index] == 0)) { index++; } else { if (index > 0) { stream.Position -= index; } index = 0; } if (index == length) { break; } } if (index == length) { m_filePos = stream.Position; m_espValue = (byte)stream.ReadByte(); return true; } } catch (Exception E) { logger.Debug(E.Message); } finally { if (stream != null) { stream.Close(); } } return false; }
public static KeyValuePair<long, long>? Detect(FileStream stream) { var byteCheckPosition = 0; long beginPosition = 0; while (stream.Position < stream.Length) { if (byteCheckPosition == 0) { beginPosition = stream.Position; } if (stream.ReadByte() == RandomizeString[byteCheckPosition]) { byteCheckPosition++; } else { byteCheckPosition = 0; } if (byteCheckPosition == RandomizeString.Length) { return new KeyValuePair<long, long>(beginPosition, stream.Position - 1); } } return null; }
public static bool Compare(string file1, string file2) { if (file1.Equals(file2)) return true; if (!File.Exists(file1) || !File.Exists(file2)) return false; FileStream first = new FileStream(file1, FileMode.Open); FileStream second = new FileStream(file2, FileMode.Open); if (first.Length != second.Length) { first.Close(); second.Close(); return false; } int byte1; int byte2; do { byte1 = first.ReadByte(); byte2 = second.ReadByte(); } while ((byte1 == byte2) && (byte1 != -1)); first.Close(); second.Close(); return (byte1 == byte2); }
static void Main() { // Создаем файл в текущем каталоге. var stream = new FileStream("Test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); // Записываем байты в файл. for (int i = 0; i < 256; i++) { stream.WriteByte((byte)i); } Console.WriteLine(stream.Position); // Переставляем внутренний указатель на начало. stream.Position = 0; // Считывам байты из файла. for (int i = 0; i < 256; i++) { Console.Write(" " + stream.ReadByte()); } // Закрываем FileStream. stream.Close(); // Delay. Console.ReadKey(); }
static byte[] SaveFileRead(string path, string fileName) { // 폴더 및 파일 체크 CSVReader.CheckFile(@path, @fileName); // 파일 경로 string fullPath = string.Format("{0}/{1}", @path, @fileName); // 파일 열기 System.IO.FileStream fs = new System.IO.FileStream(@fullPath, System.IO.FileMode.Open); // 결과물 List <byte> result = new List <byte>(); // 파일 읽기 int data; while ((data = fs.ReadByte()) != -1) { result.Add((byte)data); } // 파일 닫기 fs.Close(); // 결과 반환 return(result.ToArray()); }
public void LoadPlanesData(System.IO.FileStream fs) { int count = fs.ReadByte(); if (count > 0) { var pls = new Dictionary <byte, Plane>(); Plane p; for (byte i = 0; i < count; i++) { p = Plane.Load(fs, this); if (p != null) { pls.Add(p.faceIndex, p); } } if (pls.Count > 0) { planes = pls; } else { planes = null; } } else { planes = null; } }
/// <summary> /// Reads the file at the given path line by line. /// </summary> /// <param name="path"></param> /// <param name="encoding"></param> /// <returns></returns> public static IEnumerable<string> ReadLineByLine(string path, Encoding encoding) { bool isFirstLine = true; FileStream fs = new FileStream(path, FileMode.Open); try { int b = 0; List<byte> lineBuilder = new List<byte>(256); while ((b = fs.ReadByte()) >= 0) { if (b == '\n') { if (isFirstLine) { yield return encoding.GetString(lineBuilder.ToArray()).Substring(1); isFirstLine = false; } else { yield return encoding.GetString(lineBuilder.ToArray()); } lineBuilder.Clear(); } else if (b != '\r') { lineBuilder.Add((byte)b); } } } finally { fs.Close(); } }
/* reads a file and returns the content as string */ public static string readFromFile(string fileName) { FileStream fin=null; int i; string content=""; /* try to open the file */ try { fin=new FileStream(fileName, FileMode.Open); } catch(IOException ioe) { Console.WriteLine (ioe.Message); } /* read upto end of file */ do { i=fin.ReadByte(); if(i!=-1) content+=(char)i; } while(i!=-1); if(fin!=null) fin.Close(); return content; }
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(); } } }
// } private void Btn_Read_Click(object sender, EventArgs e) { int[] eingaben = new int[100]; // string ausgabe = ""; if (!(File.Exists(filename))) { MessageBox.Show("Datei nicht gefunden !"); } else { // Aus der Datei lesen System.IO.FileStream lesen = new System.IO.FileStream(filename, System.IO.FileMode.Open); int i = 0; // eingaben[0] = 0; do { if (eingaben[i] != -1) { eingaben[i] = lesen.ReadByte(); ausgabe += (char)eingaben[i]; } i++; }while (eingaben[i - 1] != -1); lesen.Close(); TBx_file.Text = ausgabe; } }
public static Quest Load(System.IO.FileStream fs) { Quest q = new Quest((QuestType)fs.ReadByte(), (byte)fs.ReadByte()); var data = new byte[4]; fs.Read(data, 0, 4); int stepsCount = System.BitConverter.ToInt32(data, 0); data = new byte[stepsCount]; fs.Read(data, 0, data.Length); q.stepsFinished = new bool[stepsCount]; for (int i = 0; i < stepsCount; i++) { q.stepsFinished[i] = data[i] == 1; } return(q); }
//Returns -1 if the file does not end with $$$$\n or if it can not be read from MoleculeStream as MDLMOL internal static long FindNextPosition(System.IO.FileStream istr, long startpos) { //FileChannel fch = istr.getChannel(); //fch.position(startpos); istr.Seek(startpos, SeekOrigin.Begin); long pos = startpos; long size = istr.Length; // fch.Count long nextpos = -1; System.String rec = ""; while (nextpos < size) { int inp = istr.ReadByte(); pos++; if (inp < 0) { break; } char ch = (char)inp; if (ch == '\r') { continue; } rec = System.String.Concat(rec, System.Convert.ToString(ch)); if (rec.EndsWith("$$$$\n")) { nextpos = pos; break; } } if (nextpos < 0) { return(-1); } try { //UPGRADE_ISSUE: Constructor 'java.io.StreamReader.StreamReader' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioBufferedReaderBufferedReader_javaioReader'" using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(rec))) { using (StreamReader input = new StreamReader(stream)) { Molecule mol = ReadMDLMOL(input); if (mol == null) { nextpos = -1; } } } } catch (System.IO.IOException) { nextpos = -1; } return(nextpos); }
/// <summary> /// 判断文件流是否为UTF8字符集 /// </summary> /// <param name="sbInputStream">文件流</param> /// <returns>判断结果</returns> public static bool IsUTF8(this System.IO.FileStream sbInputStream) { int i; byte cOctets; // octets to go in this UTF-8 encoded character byte chr; bool bAllAscii = true; long iLen = sbInputStream.Length; cOctets = 0; for (i = 0; i < iLen; i++) { chr = (byte)sbInputStream.ReadByte(); if ((chr & 0x80) != 0) { bAllAscii = false; } if (cOctets == 0) { if (chr >= 0x80) { do { chr <<= 1; cOctets++; }while ((chr & 0x80) != 0); cOctets--; if (cOctets == 0) { return(false); } } } else { if ((chr & 0xC0) != 0x80) { return(false); } cOctets--; } } if (cOctets > 0) { return(false); } if (bAllAscii) { return(false); } return(true); }
public override int ReadByte() { if (_m_disposed) { throw ADP.ObjectDisposed(this); } return(_m_fs.ReadByte()); }
///// <summary> ///// Reads and outputs the contents of the specified file. ///// </summary> ///// <param name="fileName">The file name of the file to be read.</param> ///// <returns>Returns the length of the data read.</returns> //public static int OutputFile(string fileName) //{ // int length = -1; // try // { // string contents = ReadContents(fileName); // System.Web.HttpContext.Current.Response.Write(contents); // length = (int)contents.Length; // } // catch // { // } // return length; //} ///// <summary> ///// Returns an OrderedMap with the pathnames that match the specified pattern. ///// </summary> ///// <param name="pattern">The search pattern.</param> ///// <returns>Returns an OrderedMap with the pathnames that match the specified pattern.</returns> //public static OrderedMap Glob(string pattern) //{ // OrderedMap newOrderedMap = null; // try // { // string path = // System.Web.HttpContext.Current.Request.MapPath( // System.Web.HttpContext.Current.Request.ApplicationPath); // System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(path)); // System.IO.FileSystemInfo[] fileInfos = dirInfo.GetFiles(pattern); // if (fileInfos.Length > 0) // { // newOrderedMap = new OrderedMap(); // for (int index = 0; index < fileInfos.Length; index++) // newOrderedMap[index] = fileInfos[index].Name; // } // } // catch // { // } // return newOrderedMap; //} ///// <summary> ///// Reads the specified INI file and returns the contents in an OrderedMap. ///// </summary> ///// <param name="fileName">The INI file to read.</param> ///// <returns>Returns the contents of the specified INI file.</returns> //public static OrderedMap ParseINI(string fileName) //{ // OrderedMap newOrderedMap = null; // try // { // using (System.IO.StreamReader stream = new System.IO.StreamReader(fileName)) // { // newOrderedMap = new OrderedMap(); // string line; // while ((line = stream.ReadLine()) != null) // { // line = line.Trim(); // if (line != "" && !line.StartsWith(";") && !line.StartsWith("[")) // { // string[] lineContents = line.Split('='); // newOrderedMap[lineContents[0].Trim()] = lineContents[1].Trim(); // } // } // } // } // catch // { // } // return newOrderedMap; //} /// <summary> /// Reads a line from the specified stream. /// Reading ends when one of the following conditions is met: /// <list type="bullet"> /// <item>Length - 1 bytes have been read.</item> /// <item>On a newline.</item> /// <item>On EOF.</item> /// </list> /// </summary> /// <param name="stream">The stream to read from.</param> /// <param name="length">The maximum length of the line to be read.</param> /// <returns>Returns a string value that represents a line.</returns> public static string ReadLine(System.IO.FileStream stream, int length) { string line = null; try { int count = 0; bool endOfLine = false; while (!endOfLine) { if (stream.Position < stream.Length && count < length) { //A line is defined as a sequence of characters followed by: // a carriage return (hexadecimal 0x000d) // a line feed (hexadecimal 0x000a) // or carriage return + line feed (hexadecimal 0x000d 0x000a) byte theByte = (byte)stream.ReadByte(); if (theByte == (byte)0x0d || theByte == (byte)0x0a) { byte nextByte = (byte)stream.ReadByte(); if (nextByte != (byte)0x0a) { stream.Position--; //if line ends with 0x000d 0x000a, then consume 0x000a. } endOfLine = true; } else { line += System.Text.Encoding.ASCII.GetString(new byte[] { theByte }); } } else { endOfLine = true; } } } catch { } return(line); }
public void Load(System.IO.FileStream fs) { int questsCount = (int)QuestSection.TotalCount; //access mask questAccessMap = new bool[questsCount]; var data = new byte[questsCount]; fs.Read(data, 0, data.Length); for (int i = 0; i < questsCount; i++) { questAccessMap[i] = data[i] == 1; } //completeness mask data = new byte[4]; fs.Read(data, 0, 4); int count = System.BitConverter.ToInt32(data, 0); uint[] mask = new uint[count]; for (int i = 0; i < count; i++) { fs.Read(data, 0, 4); mask[i] = System.BitConverter.ToUInt32(data, 0); } Quest.SetCompletenessMask(mask); //active quests activeQuests = new Quest[questsCount]; for (int i = 0; i < questsCount; i++) { activeQuests[i] = Quest.NoQuest; var marker = fs.ReadByte(); if (marker != 0) { if (marker != 2) { activeQuests[i] = Quest.Load(fs); } else { StartCoroutine(WaitForNewQuest(i)); } } else { if (questAccessMap[i] == true) { StartCoroutine(WaitForNewQuest(i)); } } } }
// Reading String from File public static string ReadNullTerminated(this System.IO.FileStream rdr) { var bldr = new System.Text.StringBuilder(); int nc; while ((nc = rdr.ReadByte()) > 0) { bldr.Append((char)nc); } return(bldr.ToString()); }
override public void Load(System.IO.FileStream fs, Plane sblock) { var data = new byte[STRUCTURE_SERIALIZER_LENGTH + BUILDING_SERIALIZER_LENGTH + WORKBUILDING_SERIALIZER_LENGTH]; fs.Read(data, 0, data.Length); LoadStructureData(data, sblock); LoadBuildingData(data, STRUCTURE_SERIALIZER_LENGTH); LoadWorkBuildingData(data, STRUCTURE_SERIALIZER_LENGTH + BUILDING_SERIALIZER_LENGTH); SetModelRotation(modelRotation); // load dock data correctLocation = fs.ReadByte() == 1; maintainingShip = fs.ReadByte() == 1; if (maintainingShip) { loadingShip = Ship.Load(fs, this); } data = new byte[8]; fs.Read(data, 0, 8); loadingTimer = System.BitConverter.ToSingle(data, 0); shipArrivingTimer = System.BitConverter.ToSingle(data, 4); }
/// <summary> /// Reads a byte from the file stream and advances the read position one byte. /// </summary> /// <param name="stream">The file stream to read from.</param> /// <returns>Returns the string representation of the read byte.</returns> public static string ReadByte(System.IO.FileStream stream) { string result = null; try { result = System.Text.Encoding.ASCII.GetString(new byte[] { (byte)stream.ReadByte() }); } catch { } return(result); }
public static bool CheckDllVersion(string filename, byte version) { if (!System.IO.File.Exists(Path.GetTempPath() + filename + ".txt")) { return(false); } using (System.IO.FileStream fs = new System.IO.FileStream(Path.GetTempPath() + filename + ".txt", System.IO.FileMode.Open)) { bool result = fs.ReadByte() == version; fs.Close(); return(result); } }
static public int ReadByte(IntPtr l) { try { System.IO.FileStream self = (System.IO.FileStream)checkSelf(l); var ret = self.ReadByte(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void CriarPastasRemoto(string pPath, DateTime pData, int pSala, int pPalestrante, string pHora, string pDestinoArquivo, System.IO.FileStream pArquivo, string pNomeArquivo) { string pathFinal = string.Empty; Sala sala = new SalaDAO().BuscarPorCodigo(pSala, pPath); if (sala != null) { if (!System.IO.Directory.Exists(pDestinoArquivo + @"\" + sala.Nome)) //Se não existe a pasta da sala para a data { System.IO.Directory.CreateDirectory(pDestinoArquivo + @"\" + sala.Nome); //Cria } } //System.IO.Directory.CreateDirectory(pDestinoArquivo + @"\" + @"\" + sala.Nome + ArquivoBD.FORMATARDATA_DIRETORIO(pData));//Cria if (!System.IO.Directory.Exists(pDestinoArquivo + @"\" + sala.Nome + @"\" + ArquivoBD.FORMATARDATA_DIRETORIO(pData))) //Se não existe a pasta da data { System.IO.Directory.CreateDirectory(pDestinoArquivo + @"\" + sala.Nome + @"\" + ArquivoBD.FORMATARDATA_DIRETORIO(pData)); //Cria } Palestrante palestrante = new PalestranteDAO().BuscarPorCodigo(pPalestrante, pPath); if (palestrante != null) { //Verifico se já existe a pasta para o horário if (!System.IO.Directory.Exists(pDestinoArquivo + @"\" + @"\" + sala.Nome + @"\" + ArquivoBD.FORMATARDATA_DIRETORIO(pData) + @"\" + pHora.Replace(":", "-") + @" - " + palestrante.NomeSobreNome())) //Se não existe a pasta do horário para a sala e para a data { pathFinal = System.IO.Directory.CreateDirectory(pDestinoArquivo + @"\" + sala.Nome + @"\" + ArquivoBD.FORMATARDATA_DIRETORIO(pData) + @"\" + pHora.Replace(":", "-") + @" - " + palestrante.NomeSobreNome()).FullName; //Cria } else { pathFinal = pDestinoArquivo + @"\" + @"\" + sala.Nome + @"\" + ArquivoBD.FORMATARDATA_DIRETORIO(pData) + @"\" + pHora.Replace(":", "-") + @" - " + palestrante.NomeSobreNome(); //Cria } } if (!String.IsNullOrEmpty(pNomeArquivo)) { System.IO.FileStream arquivoSaida = System.IO.File.Create(pathFinal + @"\ " + pNomeArquivo); int b; while ((b = pArquivo.ReadByte()) > -1) { arquivoSaida.WriteByte((byte)b); } arquivoSaida.Flush(); arquivoSaida.Close(); pArquivo.Close(); } }
public static RingSector[] StaticLoad(System.IO.FileStream fs) { var data = new byte[4]; fs.Read(data, 0, 4); int count = System.BitConverter.ToInt32(data, 0), readVal1 = -1, readVal2 = -1; var sectors = new RingSector[count]; MapPoint f_centralPoint = null; var gmap = GameMaster.realMaster.globalMap; for (int i = 0; i < count; i++) { readVal1 = fs.ReadByte(); if (readVal1 == 0) { continue; } else { data = new byte[14]; fs.Read(data, 0, data.Length); readVal1 = System.BitConverter.ToInt32(data, 0); readVal2 = System.BitConverter.ToInt32(data, 4); f_centralPoint = gmap.GetMapPointByID(readVal2); var rs = new RingSector(readVal1, f_centralPoint, (Environment.EnvironmentPreset)data[8]); readVal1 = System.BitConverter.ToInt32(data, 9); if (readVal1 > 0) { data = new byte[5 * readVal1 + 1]; // byte + int fs.Read(data, 0, data.Length); for (int j = 0; j < readVal1; j++) { rs.innerPointsIDs.Add(data[j * 5], System.BitConverter.ToInt32(data, 5 * j + 1)); } } rs.fertile = data[data.Length - 1] == 1; if (f_centralPoint != null) { sectors[i] = rs; } } } data = new byte[4]; fs.Read(data, 0, 4); lastFreeID = System.BitConverter.ToInt32(data, 0); return(sectors); }
public void LoadPlanesData(System.IO.FileStream fs) { var count = fs.ReadByte(); if (count > 0) { IPlanableSupportClass.AddBlockRepresentation(this, basement, ref myBlock, false); planes = new Dictionary <byte, Plane>(); for (int i = 0; i < count; i++) { var p = Plane.Load(fs, this); planes.Add(p.faceIndex, p); } } }
public static void LoadDockSystem(System.IO.FileStream fs) { current = null; int x = fs.ReadByte(); if (x == 0) { return; } else { current = new DockSystem(); current.Load(fs); } }
/// <summary> /// Compares two files by reading all bytes, and comparing one by one /// </summary> /// <param name="f1">One file</param> /// <param name="f2">Another file</param> /// <param name="display">File display name</param> /// <returns>True if they are equal, false otherwise</returns> public static bool CompareFiles(string f1, string f2, string display, bool verifymetadata) { using (System.IO.FileStream fs1 = System.IO.File.OpenRead(f1)) using (System.IO.FileStream fs2 = System.IO.File.OpenRead(f2)) if (fs1.Length != fs2.Length) { Log.WriteErrorMessage(LOGTAG, "LengthsDiffer", null, "Lengths differ: {0}, {1} vs {2}", display, fs1.Length.ToString(), fs2.Length.ToString()); Console.WriteLine("Lengths differ: " + display + ", " + fs1.Length.ToString() + " vs. " + fs2.Length.ToString()); return(false); } else { // The byte-by-byte compare is dog-slow, so we use a fast(-er) check, and then report the first byte diff if required if (!Library.Utility.Utility.CompareStreams(fs1, fs2, true)) { fs1.Position = 0; fs2.Position = 0; long len = fs1.Length; for (long l = 0; l < len; l++) { if (fs1.ReadByte() != fs2.ReadByte()) { Log.WriteErrorMessage(LOGTAG, "MismatchInFile", null, "Mismatch in byte {0} in file {1}", l.ToString(), display); Console.WriteLine("Mismatch in byte " + l.ToString() + " in file " + display); return(false); } } } } if (verifymetadata) { if (System.IO.File.GetLastWriteTime(f1) != System.IO.File.GetLastWriteTime(f2)) { Log.WriteWarningMessage(LOGTAG, "MismatchInLastModified", null, "Mismatch in lastmodified for {0}, {1} vs {2}", f2, System.IO.File.GetLastWriteTimeUtc(f1), System.IO.File.GetLastWriteTimeUtc(f2)); Console.WriteLine("Mismatch in lastmodified for " + f2 + ", " + System.IO.File.GetLastWriteTimeUtc(f1) + " vs. " + System.IO.File.GetLastWriteTimeUtc(f2)); } if (System.IO.File.GetCreationTimeUtc(f1) != System.IO.File.GetCreationTimeUtc(f2)) { Log.WriteWarningMessage(LOGTAG, "MismatchInCreateTime", null, "Mismatch in create-time for {0}, {1} vs {2}", f2, System.IO.File.GetCreationTimeUtc(f1), System.IO.File.GetCreationTimeUtc(f2)); Console.WriteLine("Mismatch in create-time for " + f2 + ", " + System.IO.File.GetCreationTimeUtc(f1) + " vs. " + System.IO.File.GetCreationTimeUtc(f2)); } } return(true); }
private void Btn_Verschl_Click(object sender, EventArgs e) { int anz = 100; int[] eingaben = new int[anz]; // int[] verschl = new int[anz]; string ausgabe = ""; if (!(File.Exists(filename))) { MessageBox.Show("Datei nicht gefunden !"); } else { // Aus der Datei lesen System.IO.FileStream lesen = new System.IO.FileStream(filename, System.IO.FileMode.Open); int len = 0; for (int i = 1; eingaben[i - 1] != -1; i++) { eingaben[i] = lesen.ReadByte(); verschl[i] = eingaben[i] + 1; // Die Verschlüsselung ausgabe += (char)(verschl[i] /*eingaben[i]*/); len = i; } lesen.Close(); TBx_file.Text = ausgabe; string fileverschl = "C:\\Temp\\Verschluessel.txt"; // Den verschlüsselten Text speichern System.IO.FileStream schreiben = new System.IO.FileStream (fileverschl, System.IO.FileMode.Create); for (int i = 1; i < len; i++) { schreiben.WriteByte(Convert.ToByte(verschl[i])); } schreiben.Close(); if (File.Exists(fileverschl)) { MessageBox.Show("Die Verschlüsselung wurde kopiert !"); } else { MessageBox.Show("ERROR: Verschlüsselung wurde nicht gespeichert !"); } } }
public static string Test07() { if (File.Exists("test.txt")) { File.Delete("test.txt"); } using (System.IO.FileStream fs = new System.IO.FileStream("test.txt", System.IO.FileMode.Create)) { fs.WriteByte(100); } using (System.IO.FileStream fs = new System.IO.FileStream("test.txt", System.IO.FileMode.Open)) { return(fs.ReadByte().ToString()); } }