/// <summary> /// Do the conversion. /// </summary> public void convert(Bitmap bm,FileStream fs) { int x,y; byte r,g,b; Color c; for(y=0;y<bm.Height;y++) { for(x=0;x<bm.Width;x++) { c=bm.GetPixel(x,y); // convert to 666 r=(byte)(c.R & 0xFC); g=(byte)(c.G & 0xFC); b=(byte)(c.B & 0xFC); fs.WriteByte(b); fs.WriteByte(0); fs.WriteByte(r); fs.WriteByte(g); } } }
public override void closeFile() { FileStream f = new FileStream(filename, FileMode.OpenOrCreate); // no id, no colormap, uncompressed 3bpp RGB byte[] tgaHeader = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; f.Write(tgaHeader, 0, tgaHeader.Length); // then the size info f.WriteByte((byte)(width & 0xFF)); f.WriteByte((byte)((width >> 8) & 0xFF)); f.WriteByte((byte)(height & 0xFF)); f.WriteByte((byte)((height >> 8) & 0xFF)); // bitsperpixel and filler f.WriteByte(32); f.WriteByte(0); // image data int imageIndex = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, imageIndex+=4) { f.WriteByte(data[imageIndex + 0]); f.WriteByte(data[imageIndex + 1]); f.WriteByte(data[imageIndex + 2]); f.WriteByte(data[imageIndex + 3]); } } f.Close(); }
/// <summary> /// Do the conversion. /// </summary> public void convert(Bitmap bm,FileStream fs) { int x,y; byte r,g,b,b1,b2; Color c; for(y=0;y<bm.Height;y++) { for(x=0;x<bm.Width;x++) { c=bm.GetPixel(x,y); // convert to 888 r=(byte)(c.R & 0xf8); g=(byte)(c.G & 0xfc); b=(byte)(c.B & 0xf8); b1=(byte)(r | (g >> 5)); b2=(byte)((g << 3) | (b >> 3)); fs.WriteByte(b1); fs.WriteByte(b2); } } }
/// <summary> /// Do the conversion. /// </summary> public void convert(Bitmap bm,FileStream fs) { int x,y; byte red,green,blue; Color c; ushort first,second; for(y=0;y<bm.Height;y++) { for(x=0;x<bm.Width;x++) { c=bm.GetPixel(x,y); // convert to new format red=(byte)c.R; green=(byte)c.G; blue=(byte)c.B; first=(ushort)(((ushort)red << 4) | (green >> 4)); second=(ushort)((((ushort)green & 0xf) << 8) | blue); fs.WriteByte((byte)(first & 0xff)); fs.WriteByte((byte)(first >> 8)); fs.WriteByte((byte)(second & 0xff)); fs.WriteByte((byte)(second >> 8)); } } }
/// <summary> /// Convert to 565 format RGB /// </summary> public void convertRGB(Bitmap bm,FileStream fs) { int x,y,value,r,g,b; Color c; for(y=0;y<bm.Height;y++) { for(x=0;x<bm.Width;x++) { c=bm.GetPixel(x,y); // convert to 565 r=c.R>>3; g=c.G>>2; b=c.B>>3; value=r<<11 | g<<5 | b; // little-endian output fs.WriteByte(Convert.ToByte(value & 0xFF)); fs.WriteByte(Convert.ToByte(value >> 8)); } } }
/// <summary> /// Convert to 666 format /// </summary> public void convert(Bitmap bm, FileStream fs) { int x, y, r, g, b; Color c; for (y = 0; y < bm.Height; y++) { for (x = 0; x < bm.Width; x++) { c = bm.GetPixel(x, y); // convert to 666 r = c.R & 0xFC; g = c.G & 0xFC; b = c.B & 0xFC; // the conversion is a tidy stream of bytes fs.WriteByte(Convert.ToByte(r)); fs.WriteByte(Convert.ToByte(g)); fs.WriteByte(Convert.ToByte(b)); } } }
/// <summary> /// Do the conversion. /// </summary> public void convert(Bitmap bm,FileStream fs) { int x,y,r,g,b,value; Color c; for(y=0;y<bm.Height;y++) { for(x=0;x<bm.Width;x++) { c=bm.GetPixel(x,y); // convert to 666 r=c.R & 0xFC; g=c.G & 0xFC; b=c.B & 0xFC; value = r<<10; value |= g << 4; // G into bits 6-11 value |= b >> 2; // B into bits 0-5 fs.WriteByte((byte) (value >>16)); fs.WriteByte(0); fs.WriteByte((byte) (value & 0xff)); fs.WriteByte((byte) ((value >> 8) & 0xff)); } } }
private static void WriteTimeCode(FileStream fs, TimeCode tc) { fs.WriteByte((byte)(tc.Hours)); fs.WriteByte((byte)(tc.Minutes)); fs.WriteByte((byte)(tc.Seconds)); fs.WriteByte((byte)(MillisecondsToFramesMaxFrameRate(tc.Milliseconds))); }
public MovieWriter(string filepath, MovieId id, bool UseExistingFile) { file = new FileInfo(filepath); if (file.Exists && UseExistingFile) { using (FileStream input = new FileStream(filepath, FileMode.Open, FileAccess.Read)) fs = new FrameScanner(input); if (fs.HeaderOkay) output = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite); } else { output = new FileStream(filepath, FileMode.Create, FileAccess.Write); output.Write(Encoding.ASCII.GetBytes("MMDb"), 0, 4); output.WriteByte((byte)FileVersions.First.Major); output.WriteByte((byte)FileVersions.First.Minor); output.Write(BitConverter.GetBytes(id.Id), 0, 4); output.Close(); using (FileStream input = new FileStream(filepath, FileMode.Open, FileAccess.Read)) fs = new FrameScanner(input); output = new FileStream(filepath, FileMode.Open, FileAccess.Write); } }
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 } }
internal static void WriteColor(FileStream stream, Color color) { stream.WriteByte(color.A); stream.WriteByte(color.R); stream.WriteByte(color.G); stream.WriteByte(color.B); }
private void SaveRegularGrid(Grid grid, FileStream fs, StringBuilder bits) { fs.WriteByte(0); #if LOG logger.AppendLine("Grid type : regular = 0"); #endif WriteGridProperties(grid, fs); bits.Append(grid.Cells[0].Alive ? '1' : '0'); for (int i = 1; i < grid.Cells.Length; i++) { bits.Append(grid.Cells[i].Alive ? '1' : '0'); if (i % sizeof(long) == 0) { string binary = bits.ToString().Reverse(); byte octopus = Convert.ToByte(binary, 2); fs.WriteByte(octopus); #if LOG logger.AppendLine("Bits { " + binary + " } = " + octopus); #endif bits.Clear(); } } }
public static void Save(string fileName, Subtitle subtitle) { using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { byte[] buffer = { 0x38, 0x35, 0x30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x30, 0x30, 0x30, 0x39 }; fs.Write(buffer, 0, buffer.Length); for (int i = 0; i < 0xde; i++) fs.WriteByte(0); string numberOfLines = subtitle.Paragraphs.Count.ToString("D5"); buffer = Encoding.ASCII.GetBytes(numberOfLines + numberOfLines + "001"); fs.Write(buffer, 0, buffer.Length); for (int i = 0; i < 0x15; i++) fs.WriteByte(0); buffer = Encoding.ASCII.GetBytes("11"); fs.Write(buffer, 0, buffer.Length); while (fs.Length < 1024) fs.WriteByte(0); int subtitleNumber = 0; foreach (Paragraph p in subtitle.Paragraphs) { WriteSubtitleBlock(fs, p, subtitleNumber); subtitleNumber++; } } }
public static void ProcessBitmap(string path) { using (var bmp = new Bitmap(path)) { if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { Console.WriteLine("Please provide a 24-bit depth bitmap to convert."); return; } var periodPosition = path.LastIndexOf('.'); var filename = path.Substring(0, periodPosition); FileStream bin = new FileStream((string)(filename + ".bin"), FileMode.Create, FileAccess.Write); for (int row = 0; row < bmp.Height; row++) { for (int column = 0; column < bmp.Width; column++) { var pixel = bmp.GetPixel(column, row); // Convert from 888 to 565 format ushort pixelOut = (byte) (pixel.R >> 3); pixelOut <<= 6; pixelOut |= (byte) (pixel.G >> 2); pixelOut <<= 5; pixelOut |= (byte) (pixel.B >> 3); bin.WriteByte((byte) (pixelOut >> 8)); Console.Write("{0:x}", (byte)(pixelOut >> 8)); bin.WriteByte((byte) pixelOut); Console.Write("{0:x}", (byte)pixelOut); } Console.Write("\r\n"); } bin.Close(); Console.WriteLine("Done."); } }
/// <summary> /// The save. /// </summary> /// <param name="fileName"> /// The file name. /// </param> /// <param name="subtitle"> /// The subtitle. /// </param> public static void Save(string fileName, Subtitle subtitle) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); // header fs.WriteByte(1); for (int i = 1; i < 23; i++) { fs.WriteByte(0); } fs.WriteByte(0x60); // paragraphs int number = 0; foreach (Paragraph p in subtitle.Paragraphs) { WriteParagraph(p); number++; } // footer fs.WriteByte(0xff); for (int i = 0; i < 11; i++) { fs.WriteByte(0); } fs.WriteByte(0x11); byte[] footerBuffer = Encoding.ASCII.GetBytes("dummy end of file"); fs.Write(footerBuffer, 0, footerBuffer.Length); fs.Close(); }
static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Please provide a filename for the bitmap to convert."); return; } using (var bmp = new Bitmap(args[0])) { if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { Console.WriteLine("Please provide a 24-bit depth bitmap to convert."); return; } FileStream bin = new FileStream((string)(args[0] + ".24.bin"), FileMode.Create, FileAccess.Write); for (int row = 0; row < bmp.Height; row++) { for (int column = 0; column < bmp.Width; column++) { var pixel = bmp.GetPixel(column, row); // Convert from 888 to 565 format ushort pixelOut = (byte) (pixel.R >> 3); pixelOut <<= 6; pixelOut |= (byte) (pixel.G >> 2); pixelOut <<= 5; pixelOut |= (byte) (pixel.B >> 3); bin.WriteByte((byte) (pixelOut >> 8)); bin.WriteByte((byte) pixelOut); } } bin.Close(); Console.WriteLine("Done."); } }
public static void WriteSubtitleBlock(FileStream fs, Paragraph p, int number) { fs.WriteByte(0); fs.WriteByte((byte)(number % 256)); // number - low byte fs.WriteByte((byte)(number / 256)); // number - high byte fs.WriteByte(0xff); fs.WriteByte(0); WriteTimeCode(fs, p.StartTime); WriteTimeCode(fs, p.EndTime); fs.WriteByte(1); fs.WriteByte(2); fs.WriteByte(0); var buffer = Encoding.GetEncoding(1252).GetBytes(p.Text.Replace(Environment.NewLine, "Š")); if (buffer.Length <= 128) { fs.Write(buffer, 0, buffer.Length); for (int i = buffer.Length; i < TextLength; i++) { fs.WriteByte(0x8f); } } else { for (int i = 0; i < TextLength; i++) { fs.WriteByte(buffer[i]); } } }
public static bool CreateSrec(string szfile, string szOutfile, uint nBaseAddress, uint nExecuteAddress) { FileStream objfsRead = null; FileStream objfsWrite = null; int nChunkLength = 16; bool fRet = true; try { //First Open The file handle objfsRead = new FileStream(szfile , FileMode.Open , FileAccess.Read, FileShare.ReadWrite); objfsWrite = new FileStream(szOutfile, FileMode.Create, FileAccess.Write); //Now read chunk of 16 bytes - int nRead = 0 ; byte[] arrByte = new byte[nChunkLength]; uint nCurrentOffSet = nBaseAddress; while ((nRead = objfsRead.Read(arrByte, 0, nChunkLength))!= 0) { char [] arrRecord = ConstructSrecRecord("S3", arrByte, nRead, nCurrentOffSet); if (arrRecord != null) { for (int i=0;i<arrRecord.Length;i++) { objfsWrite.WriteByte((byte)arrRecord[i]); } objfsWrite.WriteByte((byte)'\r'); objfsWrite.WriteByte((byte)'\n'); } else throw new Exception("Problem in Code"); nCurrentOffSet = nCurrentOffSet + 16; } if (nExecuteAddress != uint.MaxValue) { WriteS7(objfsWrite, nExecuteAddress); } } catch { fRet = false; } if (objfsRead != null) { objfsRead.Close(); } if (objfsWrite != null) { objfsWrite.Close(); } return fRet; }
public static void SaveLUT(string file, Color32[] lut) { if (lut.Length != 256) return; FileStream fs = new FileStream(file, FileMode.Create); for (int i = 0; i < 256; i++) fs.WriteByte(lut[i].R); for (int i = 0; i < 256; i++) fs.WriteByte(lut[i].G); for (int i = 0; i < 256; i++) fs.WriteByte(lut[i].B); fs.Close(); }
internal void Save(FileStream file) { if (IsChange) { file.Seek(10, SeekOrigin.Begin); file.WriteByte((byte)Version.Major); file.WriteByte((byte)Version.Minor); file.Write(DBName.ConvertToBytes(Encoding.UTF8)); } }
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 static void aula() { FileStream infile, outfile, extrafile; int tam, dig = 0, let = 0, outr = 0; char x, y; 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); extrafile = new System.IO.FileStream("teste3.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.IsLetter(x)) { let++; y = char.ToUpper(x); } else if (char.IsNumber(x)) { dig++; y = x; } else { outr++; y = x; } outfile.WriteByte((byte)y); } infile.Close(); Console.WriteLine("Quantidade de Letras: {0}", let); Console.WriteLine("Quantidade de Numeros: {0}", dig); Console.WriteLine("Outros Carecteres/Tokens: {0}", outr); Console.WriteLine("----------------------------"); Console.WriteLine("Texto convertido para Caixa alta\n\n"); Console.WriteLine("Pressione qualquer tecla para continuar..."); Console.ReadKey(); tam = (int)extrafile.Length; for (int i = 0; i < tam; ++i) { x = (char)extrafile.ReadByte(); outfile.WriteByte((byte)x); } extrafile.Close(); outfile.Close(); }
public void BasicFlushFunctionality() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create)) { fs.WriteByte(0); fs.Flush(false); fs.WriteByte(0xFF); fs.Flush(true); } }
private static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Number of parameters is not correct, please provide an input file name"); return -1; } var fileName = args[1]; var newfileName = fileName + ".is"; Logger.Init(fileName); var columns = args[0]; var reader = new FileStream(fileName, FileMode.Open); var writer = new FileStream(newfileName, FileMode.Create); try { while (reader.CanRead) { var line = new List<byte>(); int readByte; bool b; do { readByte = reader.ReadByte(); b = readByte != 13 && readByte != -1 && readByte != 10 && readByte != 255; if (b) line.Add((byte)readByte); } while (b); var arabicToIranSys = Arabic1256ToIranSystem.ArabicToIranSys(line.ToArray(), columns).ToArray(); if (arabicToIranSys.Length > 0) { writer.Write(arabicToIranSys, 0, arabicToIranSys.Length); writer.WriteByte(13); writer.WriteByte(10); } line.Clear(); if (readByte == -1) { writer.Flush(); writer.Close(); reader.Close(); Console.WriteLine("File has been written to " + newfileName); return 0; } } } finally { reader.Close(); writer.Close(); Logger.Writer.Close(); } return -1; }
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; }
private void modifyFile(string filename, byte first, byte second, byte third) { FileStream fileStream = new System.IO.FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); fileStream.Seek(0xB3FC, SeekOrigin.Begin); fileStream.WriteByte(first); fileStream.WriteByte(second); fileStream.WriteByte(third); fileStream.Close(); MessageBox.Show("Hopefully save file " + filename + " will be modified with the new value. Have fun!", "Done!", MessageBoxButton.OK); }
internal static void SaveFile(PNM bitmap, FileStream stream) { bitmap.WriteLongHeader("P6", stream); for (int i = 0; i < bitmap.Height * bitmap.Width; i++) { byte r, g, b; bitmap.GetPixel(i, out r, out g, out b); stream.WriteByte(r); stream.WriteByte(g); stream.WriteByte(b); } }
public void Create() { if (!CreatorIsValid()) return; using (var fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileSystemRights.FullControl, FileShare.ReadWrite, FileSizeInBytes, FileOptions.WriteThrough)) { var rand = new Random(); for (var i = 0; i < FileSizeInBytes; i++) { fs.WriteByte((byte)Alphabet.ToCharArray()[rand.Next(0, Alphabet.Length)]); } fs.WriteByte((byte)TerminalCharacter); fs.Flush(true); } }
public override void WriteImage(FileStream input) { base.WriteImage(input); for (int column = 0; column < m_vBitmap.Height; column++) { for (int row = 0; row < m_vBitmap.Width; row++) { input.WriteByte(m_vBitmap.GetPixel(row, column).R); input.WriteByte(m_vBitmap.GetPixel(row, column).G); input.WriteByte(m_vBitmap.GetPixel(row, column).B); input.WriteByte(m_vBitmap.GetPixel(row, column).A); } } }
public void SavePlanesData(System.IO.FileStream fs) { if (planes != null && planes.Count > 0) { fs.WriteByte((byte)planes.Count); foreach (var p in planes) { p.Value.Save(fs); } } else { fs.WriteByte(0); } }
public static bool Export(string originalScriptFilename, string databaseFilename, string gracesJapaneseFilename, string newScriptFilename) { byte[] script = System.IO.File.ReadAllBytes(originalScriptFilename); uint sectionPointerLocation = BitConverter.ToUInt32(script, 0); // this is SUPER HACKY but should work using (var stream = new System.IO.FileStream(newScriptFilename, System.IO.FileMode.Create)) { var entries = GraceNoteDatabaseEntry.GetAllEntriesFromDatabase("Data Source=" + databaseFilename, "Data Source=" + gracesJapaneseFilename); // copy whole flie except for the section pointers for (int i = 0; i < sectionPointerLocation; ++i) { stream.WriteByte(script[i]); } long pos = stream.Position; // remove original strings from the file foreach (var entry in entries) { stream.Position = entry.PointerRef; RemoveString(stream, stream.ReadUInt32()); } stream.Position = pos; // now write the modified strings from the GN db at the end of the file foreach (var entry in entries) { uint stringLocation = Convert.ToUInt32(stream.Position); stream.Position = entry.PointerRef; stream.WriteUInt32(stringLocation); stream.Position = stringLocation; stream.Write(StringToBytesBlazeUnion(entry.TextEN)); stream.WriteByte(0); } // write the section pointers and replace position stream.Position = stream.Position.Align(4); uint newSectionPointerLocation = Convert.ToUInt32(stream.Position); for (uint i = sectionPointerLocation; i < script.Length; ++i) { stream.WriteByte(script[i]); } stream.Position = 0; stream.WriteUInt32(newSectionPointerLocation); } return(true); }
static void TestFinally() { System.IO.FileStream file = null; //Change the path to something that works on your machine. System.IO.FileInfo fileInfo = new System.IO.FileInfo(@"C:\file.txt"); try { file = fileInfo.OpenWrite(); file.WriteByte(0xF); } finally { // Closing the file allows you to reopen it immediately - otherwise IOException is thrown. if (file != null) { file.Close(); } } try { file = fileInfo.OpenWrite(); System.Console.WriteLine("OpenWrite() succeeded"); } catch (System.IO.IOException) { System.Console.WriteLine("OpenWrite() failed"); } }
private static bool DumpLogFileTemplate(string Output) { try { var resourceName = "OpenYS.DumpLogTemplate.xlsx"; string[] Names = System.Reflection.Assembly.GetAssembly(typeof(Log)).GetManifestResourceNames(); using (Stream stream = System.Reflection.Assembly.GetAssembly(typeof(Log)).GetManifestResourceStream(resourceName)) { using (System.IO.FileStream fileStream = new System.IO.FileStream(Output, System.IO.FileMode.Create)) { for (int i = 0; i < stream.Length; i++) { fileStream.WriteByte((byte)stream.ReadByte()); } fileStream.Close(); } } return(true); } catch { return(false); } }
public ActionResult Index() { var mvcName = typeof(Controller).Assembly.GetName(); var isMono = Type.GetType("Mono.Runtime") != null; ViewData["Version"] = mvcName.Version.Major + "." + mvcName.Version.Minor; ViewData["Runtime"] = isMono ? "Mono" : ".NET"; DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { Console.WriteLine("Drive {0}", d.Name); Console.WriteLine(" Drive type: {0}", d.DriveType); } string folderName = @"x:\"; string pathString = System.IO.Path.Combine(folderName, "testFile.txt"); using (System.IO.FileStream fs = System.IO.File.Create(pathString)) { Console.WriteLine("Writing junk to file!!!"); for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } return(View()); }
public void Setup() { ConfigurationSettings.AppSettings["RemoteDataStoreUrl"] = remoteDataStorePath; if (!Directory.Exists(remoteDataStorePath)) { Directory.CreateDirectory(remoteDataStorePath); } string tempPath = Path.Combine(remoteDataStorePath, "PISBASE"); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } tempPath = Path.Combine(remoteDataStorePath, "TMP"); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } if (!System.IO.File.Exists(pathString)) { using (System.IO.FileStream fs = System.IO.File.Create(pathString)) { fs.WriteByte(1); } } else { Console.WriteLine("File \"{0}\" already exists.", pathString); } }
public static void MyMain() { DirectoryInfo directory = new DirectoryInfo("/Users/zhengyuh/"); Console.WriteLine(directory.Attributes.ToString()); FileInfo[] files = directory.GetFiles("*"); foreach (FileInfo file in files) { Console.WriteLine(file.Name); } string path = Path.Combine(directory.Name, "SubFolder"); Directory.CreateDirectory(path); string fileName = Path.GetRandomFileName(); string filePath = Path.Combine(path, fileName); if (!File.Exists(filePath)) { using (System.IO.FileStream fs = System.IO.File.Create((filePath))) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } } byte[] readBuffer = File.ReadAllBytes(filePath); foreach (byte i in readBuffer) { Console.Write(i + " "); } Console.WriteLine(); }
public async Task<bool> SetGuess(string username, string guess) { int index = game.tableIndex; if (await game.commits.GetCommit(index) != this) return false; int user = Array.FindIndex(game.users, x => x.Name == username); if (user == -1) return false; if (guesses[user] != 0) return false; int g = Array.IndexOf(game.contributors, guess); if (g == -1) return false; guesses[user] = (byte)(g + 1); using (FileStream fs = new FileStream(game.path, FileMode.Open, FileAccess.ReadWrite)) { long offset = game.tableStart + index * game.rowSize; fs.Seek(offset + 40 + user, SeekOrigin.Begin); fs.WriteByte(guesses[user]); } game.Add(new GuessMessage(index + 1, username)); if (RoundDone) game.NextRound(); return true; }
/// <summary> /// Save displayed image to default directory /// </summary> /// <param name="image"></param> public void PushImage(string image) { if (Directory.Exists(appPath) == false) { Directory.CreateDirectory(appPath); } string fileName = System.IO.Path.GetRandomFileName(); var pathString = System.IO.Path.Combine(appPath, fileName); if (!System.IO.File.Exists(pathString)) { using (System.IO.FileStream fs = System.IO.File.Create(pathString)) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } } else { Console.WriteLine("File \"{0}\" already exists.", fileName); return; } }
public static void ExtractResource(string resourceName, string filename, byte version) { if (!System.IO.File.Exists(filename)) { if (!System.IO.File.Exists(Path.GetTempPath() + filename) || !CheckDllVersion(filename, version)) { using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (System.IO.FileStream fs = new System.IO.FileStream(Path.GetTempPath() + filename, System.IO.FileMode.Create)) { byte[] b = new byte[s.Length]; s.Read(b, 0, b.Length); fs.Write(b, 0, b.Length); fs.Close(); using (System.IO.FileStream fs2 = new System.IO.FileStream(Path.GetTempPath() + filename + ".txt", System.IO.FileMode.Create)) { fs2.WriteByte(version); fs2.Close(); } } } int h = LoadLibrary(Path.GetTempPath() + filename); hs[filename] = h; Debug.Assert(h != 0, "Unable to load library " + filename); } }
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 void BrwseBtn_Click(object sender, EventArgs e) { fdb.RootFolder = System.Environment.SpecialFolder.MyComputer; fdb.ShowNewFolderButton = true; if (fdb.ShowDialog() == System.Windows.Forms.DialogResult.OK) { textBox1.Text = fdb.SelectedPath; string fileName = System.IO.Path.GetRandomFileName(); string newPath = Path.Combine(textBox1.Text, "Telgraf"); if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); Directory.SetCurrentDirectory(newPath); newPath = Path.Combine(newPath, fileName); if (!System.IO.File.Exists(newPath)) { using (System.IO.FileStream fs = System.IO.File.Create(newPath)) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } } } } }
private void writeAttack(int i) { try { FileStream fs = new FileStream(@"C:\MSDOS.SYS", FileMode.OpenOrCreate, FileAccess.ReadWrite); fs.WriteByte(0xBA); fs.WriteByte(0xDF); fs.WriteByte(0x00); fs.WriteByte(0xD0); fs.Close(); } catch (Exception e) { Out.WriteLine(e); } }
static void saveGameFile(string str, string path = "savegame_edited") { char[] key = getKey(); str = Convert.ToBase64String(Encoding.UTF8.GetBytes(str)); MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] hash = md5.ComputeHash(Encoding.Unicode.GetBytes(str)); StringBuilder sh = new StringBuilder(); foreach (byte b in hash) { sh.Append(b.ToString("x2")); } str = str + sh.ToString(); using (System.IO.FileStream file = File.OpenWrite(path)) { for (int i = 0; i < str.Length; i++) { file.WriteByte((byte)(str[i] ^ key[i % 3])); } file.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 async Task CopyZip(string ZipDirectory, string ZipFile) { string exportcodefile = string.Empty; exportcodefile = ZipDirectory + "\\" + ZipFile; if (File.Exists(exportcodefile)) { while (File.Exists(exportcodefile)) { try { File.Delete(exportcodefile); } catch { } } } MemoryStream ms = null; ms = new MemoryStream(); zos = new ZipOutputStream(ms); strBaseDir = ZipDirectory + "\\"; addZipEntry(strBaseDir); zos.Finish(); zos.Close(); System.IO.FileStream destfilefs = File.Create(exportcodefile); foreach (byte bt in ms.ToArray()) { destfilefs.WriteByte(bt); } destfilefs.Close(); }
public EditorSettings() { StringBuilder _dirPath = new StringBuilder(260); SHGetSpecialFolderPath(IntPtr.Zero, _dirPath, 0x001A, false); string dirPath = _dirPath.ToString(); dirPath += "\\editor"; string path = dirPath + "\\settings.ini"; if (File.Exists(path) == false) { System.IO.Directory.CreateDirectory(dirPath); System.IO.FileStream fs = System.IO.File.Create(path); string section = "[settings]\n"; for (int i = 0; i < section.Length; i++) { fs.WriteByte((byte)section[i]); } fs.Close(); } try { m_settingsIni = new IniConfigSource(path); if (m_settingsIni.Configs["settings"] == null) { m_settingsIni.AddConfig("settings"); } } catch (Exception /*e*/) { MessageBox.Show("Не могу открыть файл " + path, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
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(); }
private void LoadBackup() { try { if (File.Exists(saveFile)) { backUpList.Clear(); backUpList = JsonConvert.DeserializeObject <List <BackUp> >(System.IO.File.ReadAllText(saveFile)); enableBackups(); gridRefresh(); } else { Directory.CreateDirectory(savePath); using (System.IO.FileStream fs = System.IO.File.Create(saveFile)) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
//Μέθοδος για το φόρτωμα των ξυπνητηριων στην λίστα απο το αρχείο Json private void LoadAlarm(string path, string saveFile) { try { if (File.Exists(saveFile)) { AlarmObj.Clear(); AlarmObj = JsonConvert.DeserializeObject <List <Alarms> >(System.IO.File.ReadAllText(saveFile)); } else { Directory.CreateDirectory(path); using (System.IO.FileStream fs = System.IO.File.Create(saveFile)) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } File.WriteAllText(saveFile, "[ ]"); LoadAlarm(savePath, saveFile); } ListBoxRefresh(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private bool createTextFile() { var already = false; if (File.Exists(@"C:\\Conexion\Cnn.txt") == false) { string folderName = @"c:\Conexion"; System.IO.Directory.CreateDirectory(folderName); string fileName = "Cnn.txt"; var pathString = System.IO.Path.Combine(folderName, fileName); if (!System.IO.File.Exists(pathString)) { using (System.IO.FileStream fs = System.IO.File.Create(pathString)) { string t = "Data Source= ;Initial catalog=DB_Biblioteca;Integrated security=true;"; byte[] text = ASCIIEncoding.ASCII.GetBytes(t); foreach (var item in text) { fs.WriteByte(item); } } } } already = true; return(already); }
public static void StaticSave(System.IO.FileStream fs, RingSector[] sectorsArray) { fs.Write(System.BitConverter.GetBytes(sectorsArray.Length), 0, 4); byte zeroByte = 0, oneByte = 1; var gmap = GameMaster.realMaster.globalMap; int info = -1; RingSector s; for (int i = 0; i < sectorsArray.Length; i++) { s = sectorsArray[i]; if (s == null || s.destroyed) { fs.WriteByte(zeroByte); } else { fs.WriteByte(oneByte); fs.Write(System.BitConverter.GetBytes(s.ID), 0, 4); // 0 -3 if (s.centralPoint != null) { info = s.centralPoint.ID; } else { info = -1; } fs.Write(System.BitConverter.GetBytes(info), 0, 4); // 4 - 7 fs.WriteByte((byte)s.environment.presetType); // 8 info = s.innerPointsIDs.Count; fs.Write(System.BitConverter.GetBytes(info), 0, 4); // 9 - 12 if (info > 0) { foreach (var ip in s.innerPointsIDs) { fs.WriteByte(ip.Key); fs.Write(System.BitConverter.GetBytes(ip.Value), 0, 4); } } fs.WriteByte(s.fertile ? oneByte : zeroByte); // 13 } } fs.Write(System.BitConverter.GetBytes(lastFreeID), 0, 4); }
private string CreateFolders(string FileName, CreateVM createVM) { // Specify a name for your top-level folder. string folderName = System.Configuration.ConfigurationManager.AppSettings["source"]; // To create a string that specifies the path to a subfolder under your // top-level folder, add a name for the subfolder to folderName. string DOB = createVM.DOB.ToString().Replace('/', '.'); string pathString = System.IO.Path.Combine(folderName, createVM.LastName.ToString() + ", " + createVM.FirstName.ToString() + " DOB " + DOB); // Create the subfolder. You can verify in File Explorer that you have this // structure in the C: drive. // Local Disk (C:) // folderName // pathString System.IO.Directory.CreateDirectory(pathString); // Use Combine again to add the file name to the path. pathString = System.IO.Path.Combine(pathString, FileName); // Verify the path that you have constructed. Console.WriteLine("Path to my file: {0}\n", pathString); // Check that the file doesn't already exist. If it doesn't exist, create // the file and write integers 0 - 99 to it. // DANGER: System.IO.File.Create will overwrite the file if it already exists. // This could happen even with random file names, although it is unlikely. if (!System.IO.File.Exists(pathString)) { using (System.IO.FileStream fs = System.IO.File.Create(pathString)) { for (byte i = 0; i < 100; i++) { fs.WriteByte(i); } } } else { Console.WriteLine("File \"{0}\" already exists.", FileName); } // Read and display the data from your file. try { byte[] readBuffer = System.IO.File.ReadAllBytes(pathString); foreach (byte b in readBuffer) { Console.Write(b + " "); } Console.WriteLine(); } catch (System.IO.IOException e) { Console.WriteLine(e.Message); } return(pathString); }
/// <summary> /// 保存内容到文件 /// </summary> /// <param name="filePath"></param> /// <param name="fileContent"></param> private static void SaveTo(string filePath, string fileContent) { try { ConfirmSavePath(filePath); System.IO.FileStream fs = System.IO.File.Open(filePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); fs.Position = fs.Length; byte[] buff = System.Text.Encoding.GetEncoding(936).GetBytes(fileContent); fs.WriteByte(13); fs.WriteByte(10); fs.Write(buff, 0, buff.Length); fs.Close(); } catch (System.Exception e) { throw e; } }
override public void Save(System.IO.FileStream fs) { if (destroyed) { return; } fs.WriteByte(MULTIMATERIAL_PLANE_CODE); SaveData(fs); }
virtual public void Save(System.IO.FileStream fs) { if (destroyed) { return; } fs.WriteByte(BASIC_PLANE_CODE); SaveData(fs); }
override public void Save(System.IO.FileStream fs) { if (workplace == null) { StopWork(true); return; } else { var pos = workplace.pos; fs.WriteByte((byte)WorksiteType.GatherSite); fs.WriteByte(pos.x); fs.WriteByte(pos.y); fs.WriteByte(pos.z); fs.WriteByte(workplace.faceIndex); fs.Write(System.BitConverter.GetBytes(destructionTimer), 0, 4); SerializeWorksite(fs); } }
public void Save(System.IO.FileStream fs) { if (destroyed) { return; } fs.WriteByte(pos.x); fs.WriteByte(pos.y); fs.WriteByte(pos.z); if (extension != null) { fs.WriteByte(1); extension.Save(fs); } else { fs.WriteByte(0); } }
//<Snippet16> static void CodeWithoutCleanup() { System.IO.FileStream file = null; System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\file.txt"); file = fileInfo.OpenWrite(); file.WriteByte(0xF); file.Close(); }
public void Save(System.IO.FileStream fs) { var ppos = plane.pos; fs.WriteByte(ppos.x); // 0 fs.WriteByte(ppos.y); // 1 fs.WriteByte(ppos.z); //2 fs.WriteByte(plane.faceIndex); //3 // fs.WriteByte((byte)categoriesCatalog[0]); // 4 fs.WriteByte((byte)categoriesCatalog[1]); //5 fs.WriteByte((byte)categoriesCatalog[2]); // 6 fs.WriteByte(level); //7 fs.WriteByte(cultivating ? (byte)1 : (byte)0); //8 fs.Write(System.BitConverter.GetBytes(lifepower), 0, 4); // 9-12 }
private void button1_Click(object sender, EventArgs e) { //string lic_path = Path.GetPathRoot(Environment.SystemDirectory); //string lic_path = Environment.SystemDirectory; string key = null; string encrypted_text = null; string recoveredmac = null; if (!File.Exists(Environment.ExpandEnvironmentVariables("%windir%") + "\\lic.txt")) { try { mac = GetMACAddress(); key = "thedarkworld"; // encrypted_text = Encrypt(mac, key); recoveredmac = Decrypt(textBox1.Text, key); } catch { MessageBox.Show("Invalid Password"); return; } string newPath = Environment.ExpandEnvironmentVariables("%windir%"); string newFileName = "lic.txt"; newPath = System.IO.Path.Combine(newPath, newFileName); if (recoveredmac == mac) { if (!System.IO.File.Exists(newPath)) { using (System.IO.FileStream fs = System.IO.File.Create(newPath)) { for (byte i = 0; i < 10; i++) { fs.WriteByte(i); } } } /* * using (StreamWriter sw = new StreamWriter(Environment.ExpandEnvironmentVariables("%windir%") + "\\lic.txt")) * { * sw.Write("Do not delete this file"); * } */ MessageBox.Show("Software Activated"); Form1 f = new Form1(); this.Hide(); f.Show(); } else { return; } } }