Beispiel #1
0
        public void CreateFromDirectory( string Dir, string Outfile )
        {
            string[] Filepaths = System.IO.Directory.GetFiles( Dir );

            ushort Filecount = (ushort)Filepaths.Length;
            uint RequiredBytesForHeader = Util.Align( Filecount * 4u + 4u, 0x50u ); // pretty sure this is not right but should work
            var Filestream = new System.IO.FileStream( Outfile, System.IO.FileMode.Create );

            // header
            Filestream.WriteByte( (byte)'S' ); Filestream.WriteByte( (byte)'C' );
            Filestream.WriteByte( (byte)'M' ); Filestream.WriteByte( (byte)'P' );
            uint TotalFilesize = RequiredBytesForHeader;
            foreach ( string Path in Filepaths ) {
                Filestream.Write( BitConverter.GetBytes( TotalFilesize ), 0, 4 );
                TotalFilesize += (uint)( new System.IO.FileInfo( Path ).Length );
                TotalFilesize = TotalFilesize.Align( 0x10u );
            }
            while ( Filestream.Length < RequiredBytesForHeader ) { Filestream.WriteByte( 0x00 ); }

            // files
            foreach ( string Path in Filepaths ) {
                var File = new System.IO.FileStream( Path, System.IO.FileMode.Open );
                Util.CopyStream( File, Filestream, (int)File.Length );
                File.Close();
                while ( Filestream.Length % 0x10 != 0 ) { Filestream.WriteByte( 0x00 ); }
            }

            Filestream.Close();
        }
        private static void Record(long startTime, long stopTime, string name)
        {
            System.IO.FileStream fs = new System.IO.FileStream("E:/Config.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
            int r = fs.Read(new byte[102400], 0, 102400);

            if (r > 0)
            {
                fs.WriteByte(13);
                fs.WriteByte(10);
            }
            byte[] buffer = System.Text.Encoding.Default.GetBytes(name + "	"+ ",	"+ ((float)(stopTime - startTime)) / 10000000);
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();
        }
        public static int Execute(List <string> args)
        {
            if (args.Count < 2)
            {
                Console.WriteLine("Usage: ByteHotfix [filename] [location-byte] [location-byte] etc.");
                Console.WriteLine("example: ByteHotfix file.ext 77D0-20 77D1-45 77D2-46 77D3-FF");
                return(-1);
            }

            try {
                string inFilename = args[0];

                using (var fi = new System.IO.FileStream(inFilename, System.IO.FileMode.Open)) {
                    for (int i = 1; i < args.Count; i++)
                    {
                        String[] v        = args[i].Split(new char[] { '-' });
                        int      location = int.Parse(v[0], NumberStyles.AllowHexSpecifier);
                        byte     value    = byte.Parse(v[1], NumberStyles.AllowHexSpecifier);
                        fi.Position = location;
                        fi.WriteByte(value);
                    }
                    fi.Close();
                }

                return(0);
            } catch (Exception ex) {
                Console.WriteLine("Exception: " + ex.Message);
                return(-1);
            }
        }
Beispiel #4
0
        public 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");
            }
        }
Beispiel #5
0
 private void cmiDownload_Click(object sender, EventArgs e)
 {
     try
     {
         if (picShow.Image != null)
         {
             saveFileDialog1.FileName = "pic.jpg";
             saveFileDialog1.Title    = "图片下载";
             if (saveFileDialog1.FileName != string.Empty && saveFileDialog1.ShowDialog() == DialogResult.OK)
             {
                 string outpath          = saveFileDialog1.FileName;
                 System.IO.FileStream fs = new System.IO.FileStream(outpath, System.IO.FileMode.Create);
                 byte[] imageByte        = UCTemplatePic.ImageToByte(picShow.Image);
                 for (int i = 0; i < imageByte.Length; i++)
                 {
                     fs.WriteByte(imageByte[i]);
                 }
                 fs.Close();
                 ShowInfoMessage("文件下载成功");
             }
         }
     }
     catch (Exception E)
     {
         this.ShowMessage(E.Message);
     }
 }
        static void Executar()
        {
            try
            {
                // Try to access a resource.
            }
            catch (System.UnauthorizedAccessException e)
            {
                // Call a custom error logging procedure.
                LogError(e);
                // Re-throw the error.
                throw;
            }

            System.IO.FileStream file     = null;
            System.IO.FileInfo   fileinfo = new System.IO.FileInfo("C:\\file.txt");
            try
            {
                file = fileinfo.OpenWrite();
                file.WriteByte(0xF);
            }
            finally
            {
                // Check for null because OpenWrite might have failed.
                if (file != null)
                {
                    file.Close();
                }
            }
        }
Beispiel #7
0
        public void GenerateFiles(String Outdir)
        {
            System.IO.Directory.CreateDirectory(Outdir);
            for (int i = 0; i < FileData.Count; ++i)
            {
                RTDPfile r     = FileData[i];
                uint     start = r.Pointer;
                uint     end   = r.Pointer + r.Size;
                uint     count = r.Size;

                string outfilename = r.Name;

                string outpath = System.IO.Path.Combine(Outdir, outfilename);
                var    fs      = new System.IO.FileStream(outpath, System.IO.FileMode.Create);

                for (int j = 0; j < count; ++j)
                {
                    fs.WriteByte((byte)(File[start + j] ^ Xorbyte));
                }
                fs.Close();
            }

            // write filename order
            List <string> Filenames = new List <string>();

            foreach (RTDPfile r in FileData)
            {
                Filenames.Add(r.Name);
            }
            System.IO.File.WriteAllLines(Outdir + ".fileorder", Filenames.ToArray());
        }
        public static int Execute( List<string> args )
        {
            if ( args.Count < 2 ) {
                Console.WriteLine( "Usage: ByteHotfix [filename] [location-byte] [location-byte] etc." );
                Console.WriteLine( "example: ByteHotfix 325.new 3A9A3-94 3AA72-A4 3AA73-32 3AB53-51" );
                return -1;
            }

            /*
            args = new string[] { @"c:\#gn_chat\scenario.dat.ext.ex\325.new" ,
                "3A9A3-94", "3AA72-A4", "3AA73-32", "3AB53-51" };
             */

            try {
                string inFilename = args[0];

                using ( var fi = new System.IO.FileStream( inFilename, System.IO.FileMode.Open ) ) {
                    for ( int i = 1; i < args.Count; i++ ) {
                        String[] v = args[i].Split( new char[] { '-' } );
                        int location = int.Parse( v[0], NumberStyles.AllowHexSpecifier );
                        byte value = byte.Parse( v[1], NumberStyles.AllowHexSpecifier );
                        fi.Position = location;
                        fi.WriteByte( value );
                    }
                    fi.Close();
                }

                return 0;

            } catch ( Exception ex ) {
                Console.WriteLine( "Exception: " + ex.Message );
                return -1;
            }
        }
        //check the config file if there is a path to launch
        private void configFile()
        {
            path =  "config.ini";
            if (System.IO.File.Exists(path))
            {
                try
                {
                    if (new System.IO.FileInfo(path).Length > 0)
                    {
                        using (var reader = new System.IO.StreamReader(path))
                        {
                            file = String.Empty;
                            file = reader.ReadLine();
                            if (System.IO.File.Exists(file))
                            {

                                setStartupAutoPlay = true;
                            }
                            else
                                file = String.Empty;
                        }
                    }
                    
                } catch (Exception e)
                {
                    throw new ApplicationException("The config file does not point to an available file or file was deleted / moved", e);
                }
            }
            else
            {
                System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.CreateNew);
                fs.WriteByte(0);
                fs.Close();
            }
        }
Beispiel #10
0
        static void CodeWithCleanup()
        {
            /*
             * To turn the previous code into a try-catch-finally statement,
             * the cleanup code is separated from the working code, as follows.
             */

            System.IO.FileStream file     = null;
            System.IO.FileInfo   fileInfo = null;

            try
            {
                fileInfo = new System.IO.FileInfo("C:\\file.txt");

                file = fileInfo.OpenWrite();
                file.WriteByte(0xF);
            }
            catch (System.UnauthorizedAccessException e)
            {
                System.Console.WriteLine(e.Message);
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
            }
        }
Beispiel #11
0
        public void CreateFromDirectory( string Dir, string Outfile )
        {
            string[] Filepaths = System.IO.Directory.GetFiles( Dir );

            ushort Filecount = (ushort)Filepaths.Length;
            uint RequiredBytesForHeader = Util.Align( Filecount * 3u + 5u, 0x10u ); // 3 bytes per filesize + 3 bytes for an extra pointer to first file + 2 bytes for filecount
            var Filestream = new System.IO.FileStream( Outfile, System.IO.FileMode.Create );

            // header
            Filestream.Write( BitConverter.GetBytes( Filecount ), 0, 2 );
            Filestream.Write( Util.GetBytesForUInt24( RequiredBytesForHeader ), 0, 3 );
            uint TotalFilesize = RequiredBytesForHeader;
            foreach ( string Path in Filepaths ) {
                TotalFilesize += (uint)( new System.IO.FileInfo( Path ).Length );
                Filestream.Write( Util.GetBytesForUInt24( TotalFilesize ), 0, 3 );
                TotalFilesize = TotalFilesize.Align( 0x10u );
            }
            while ( Filestream.Length < RequiredBytesForHeader ) { Filestream.WriteByte( 0x00 ); }

            // files
            foreach ( string Path in Filepaths ) {
                var File = new System.IO.FileStream( Path, System.IO.FileMode.Open );
                Util.CopyStream( File, Filestream, (int)File.Length );
                File.Close();
                while ( Filestream.Length % 0x10 != 0 ) { Filestream.WriteByte( 0x00 ); }
            }

            Filestream.Close();
        }
Beispiel #12
0
        /// <summary>
        /// 保存pic为Icon图像,尺寸rect,保存文件路径名称PathName
        /// </summary>
        public static void SaveToIcon(Image pic, Rectangle rect, string PathName)
        {
            // Icon图像最大尺寸255
            if (rect.Width > 255 || rect.Height > 255)
            {
                return;
            }

            // 获取Icon信息
            IconInfo iconInfo = creatIconInfo(pic, rect);

            // 创建文件输出流,写入文件,生成Icon图像
            System.IO.FileStream stream = new System.IO.FileStream(PathName, System.IO.FileMode.Create);

            // 写入Icon固定部分
            ushort Reserved = 0;
            ushort Type     = 1;
            ushort Count    = 1;

            byte[] Temp = BitConverter.GetBytes(Reserved);
            stream.Write(Temp, 0, Temp.Length);
            Temp = BitConverter.GetBytes(Type);
            stream.Write(Temp, 0, Temp.Length);
            Temp = BitConverter.GetBytes((ushort)Count);
            stream.Write(Temp, 0, Temp.Length);

            // 写入Icon头信息
            stream.WriteByte(iconInfo.Width);
            stream.WriteByte(iconInfo.Height);
            stream.WriteByte(iconInfo.ColorNum);
            stream.WriteByte(iconInfo.Reserved);
            Temp = BitConverter.GetBytes(iconInfo.Planes);
            stream.Write(Temp, 0, Temp.Length);
            Temp = BitConverter.GetBytes(iconInfo.PixelBit);
            stream.Write(Temp, 0, Temp.Length);
            Temp = BitConverter.GetBytes(iconInfo.ImageSize);
            stream.Write(Temp, 0, Temp.Length);
            Temp = BitConverter.GetBytes(iconInfo.ImageOffset);
            stream.Write(Temp, 0, Temp.Length);

            // 写入图形数据
            stream.Write(iconInfo.ImageData, 0, iconInfo.ImageData.Length);

            stream.Close();
        }
Beispiel #13
0
        public static bool PrimitiveFasdump(out object answer, object arg0, object arg1, object arg2)
        {
#if DEBUG
            // Don't profile the disk.
            SCode.location = "-";
#endif
            System.IO.FileStream output = System.IO.File.OpenWrite(new String((char [])arg1));
            // Slap in the expected header.
            output.WriteByte(0xFA);
            output.WriteByte(0xFA);
            output.WriteByte(0xFA);
            output.WriteByte(0xFA);
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bfmt = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            bfmt.Serialize(output, arg0);
            output.Close();
            answer = Constant.sharpT;
            return(false);
        }
Beispiel #14
0
        public void MS_CreateFileOrForder()
        {
            // Specify a name for your top-level folder.
            string folderName  = @"c:\Top-Level Folder";
            string pathString  = System.IO.Path.Combine(folderName, "SubFolder");
            string pathString2 = @"c:\Top-Level Folder\SubFolder2";

            System.IO.Directory.CreateDirectory(pathString);
            string fileName = System.IO.Path.GetRandomFileName();

            //所以应该是首先GUI选择一个文件夹,然后我们在这个文件夹下面创建txt文件。
            pathString = System.IO.Path.Combine(pathString, fileName);
            //pathString 是绝对路径
            // 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);
                return;
            }

            // 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);
            }

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
Beispiel #15
0
 public void FileWrite(string sFile, string sVal)
 {
     System.IO.FileStream fs = new System.IO.FileStream(sFile, System.IO.FileMode.Create);
     for (int a = 0; a < sVal.Length; a++)
     {
         fs.WriteByte((byte)sVal[a]);
     }
     fs.Close(); fs.Dispose();
 }
Beispiel #16
0
        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();
        }
Beispiel #17
0
        private void SaveFolder(FolderModel folder)
        {
            System.IO.FileStream @out = null;
            try
            {
                @out = (System.IO.FileStream)OpenFileOutput(string.Format("folder{0:D}", folder.Id), Android.Content.FileCreationMode.Private);

                @out.WriteByte(byte.Parse(string.Format("{0:D}\n", folder.Width)));
                @out.WriteByte(byte.Parse(string.Format("{0:D}\n", folder.Height)));

                foreach (ActivityInfo appInFolder in folder.Apps)
                {
                    ComponentName name = new ComponentName(appInFolder.PackageName, appInFolder.Name);

                    @out.WriteByte(byte.Parse((name.FlattenToString() + "\n")));
                }
            }
            catch (FileNotFoundException e)
            {
                System.Console.WriteLine(e.Message);
                System.Console.Write(e.StackTrace);
            }
            catch (IOException e)
            {
                System.Console.WriteLine(e.ToString());
                System.Console.Write(e.StackTrace);
            }
            finally
            {
                if (@out != null)
                {
                    try
                    {
                        @out.Close();
                    }
                    catch (IOException e)
                    {
                        System.Console.WriteLine(e.ToString());
                        System.Console.Write(e.StackTrace);
                    }
                }
            }
        }
Beispiel #18
0
        static void CodigoSemLimpeza()
        {
            System.IO.FileStream file     = null;
            System.IO.FileInfo   fileInfo = new System.IO.FileInfo("C:\\file.txt");

            file = fileInfo.OpenWrite();
            file.WriteByte(0xF);

            file.Close();
        }
Beispiel #19
0
            public static void WriteBytes(string data, System.IO.FileStream fileStream)
            {
                int index  = 0;
                int length = data.Length;

                while (index < length)
                {
                    fileStream.WriteByte((byte)data[index++]);
                }
            }
Beispiel #20
0
        static void Main(string[] args)
        {
            LasmParser p    = new LasmParser();
            LuaFile    file = p.Parse(@"
        .const ""print""
        .const ""Hello""
        getglobal 0 0
        loadk 1 1
        call 0 2 1
        return 0 1
        ");

            file.StripDebugInfo();
            string code = file.Compile();

            try
            {
                LuaFile f = Disassembler.Disassemble(code);
                System.IO.FileStream fs = new System.IO.FileStream("lasm.luac", System.IO.FileMode.Create);
                //foreach (char c in code)
                foreach (char c in f.Compile())
                {
                    fs.WriteByte((byte)c);
                }
                fs.Close();

                // Test chunk compiling/loading
                string s    = f.Main.Compile(f);
                Chunk  chnk = Disassembler.DisassembleChunk(s);

                // Test execution of code
                string s2 = f.Compile();
                LuaRuntime.Run(s2);
                LuaRuntime.Run(code);
                Console.WriteLine("The above line should say 'Hello'. If it doesn't there is an error.");
                Console.WriteLine(LASMDecompiler.Decompile(file));
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            try
            {
                LuaFile lf = p.Parse("breakpoint 0 0 0");
                LuaRuntime.Run(lf.Compile());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Test(s) done. Press any key to continue.");
            Console.ReadKey(true);
        }
Beispiel #21
0
        public static long WriteBitmap(System.IO.FileStream fs, Bitmap bitmap)
        {
            long bytesWritten = 0;

            foreach (byte byteElem in bitmap.BitmapValue)
            {
                fs.WriteByte(byteElem);
                ++bytesWritten;
            }
            return(bytesWritten);
        }
Beispiel #22
0
 /// <summary>
 /// 将内存中的数据写入硬盘(保存特征库)
 /// </summary>
 /// <param name="thefile">保存的位置</param>
 public static void writetofile(string thefile)
 {
     System.IO.FileStream fs = new System.IO.FileStream(thefile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
     byte[] buff0            = new byte[4];
     getbytesfromint(datanum, buff0);
     fs.Write(buff0, 0, 4);
     for (int ii = 0; ii < datanum; ii++)
     {
         for (int jj = 0; jj < 20; jj++)
         {
             byte[] buff = new byte[2];
             getbytesfromushort(datap[ii, jj], buff);
             fs.Write(buff, 0, 2);
         }
         fs.WriteByte(dataxy[ii, 0]);
         fs.WriteByte(dataxy[ii, 1]);
         fs.WriteByte(datachar[ii]);
     }
     fs.Close();
 }
Beispiel #23
0
        public static string Test07()
        {
            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());
            }
        }
Beispiel #24
0
        public UploadCVResponse UploadAnexo(byte[] anexo, int becarioId, string nombreAnexo)
        {
            var response = new UploadCVResponse();

            try
            {
                var becario = _becarioRepository.GetOne(x => x.BecarioId == becarioId);
                if (becario != null)
                {
                    var ruta            = ConfigurationManager.AppSettings["rutaAnexoBecarios"].ToString();     //cogemos la ruta que hayamos definido en el Web.Config
                    var becarioIdString = becario.BecarioId.ToString();                                         // pasamos a string la candidaturaId
                    if (!System.IO.Directory.Exists(ruta))                                                      //si no existe la ruta del Web.Config
                    {
                        System.IO.Directory.CreateDirectory(ruta);                                              //la creamos
                    }
                    var rutaPosible = System.IO.Path.Combine(ruta, becarioIdString);                            //definimos un subdirectorio dentro de nuestra ruta que sea la candidaturaId
                    if (becario.NombreAnexo != null && System.IO.Directory.Exists(rutaPosible))                 //si nuestra antigua candidatura tiene algun curriculum subido y la ruta existe
                    {
                        var rutaExistente = System.IO.Path.Combine(ruta, becarioIdString, becario.NombreAnexo); // definimos la ruta hasta el nombre del curriculum anterior
                        if (System.IO.File.Exists(rutaExistente))                                               // comprobamos si este archivo existe por si hubiera habido anteriormente un fallo a mitad del procedimiento y se hubiese creado la carpeta pero no el archivo
                        {
                            System.IO.File.Delete(rutaExistente);                                               // borramos el curriculum antiguo
                        }
                    }
                    var rutaNuevoFichero = System.IO.Path.Combine(rutaPosible, nombreAnexo);  // ahora definimos la ruta con el nombre del fichero de nuestro nuevo cv
                    System.IO.Directory.CreateDirectory(rutaPosible);                         // creamos el subdirectorio con el nombre de becarioId (si ya existia no hara nada)
                    using (System.IO.FileStream fs = System.IO.File.Create(rutaNuevoFichero)) // creamos un file stream para crear nuestro nuevo fichero
                    {
                        foreach (byte i in anexo)
                        {
                            fs.WriteByte(i); //recorremos byte a byte nuestro anexo enviado y lo escribimos en la ruta especificada
                        }
                    }
                    becario.Anexo       = null; // Eliminar cuando el anexo se almacene por ruta en BD
                    becario.NombreAnexo = nombreAnexo;
                    becario.UrlAnexo    = ruta;
                    _becarioRepository.Update(becario);
                    response.IsValid = true;
                }
                else
                {
                    response.IsValid      = false;
                    response.ErrorMessage = "Failed to access the becario";
                }
            }
            catch (Exception ex)
            {
                response.IsValid      = false;
                response.ErrorMessage = ex.Message;
            }

            return(response);
        }
Beispiel #25
0
        static void Main(string[] args)

        {
            string pathString = "C:/Users/Пользователь/Desktop/papka/path/Adil.txt";

            string fileName = "Adil.txt";

            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;
            }

            string destFile = "C:/Users/Пользователь/Desktop/papka/path1/Adil.txt";

            string sourceFile = "C:/Users/Пользователь/Desktop/papka/path/Adil.txt";

            System.IO.File.Copy(sourceFile, destFile, true);

            if (System.IO.File.Exists("C:/Users/Пользователь/Desktop/papka/path/Adil.txt"))

            {
                try

                {
                    System.IO.File.Delete("C:/Users/Пользователь/Desktop/papka/path/Adil.txt");
                }

                catch (System.IO.IOException e)

                {
                    Console.WriteLine(e.Message);

                    return;
                }
            }
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            LasmParser p = new LasmParser();
            LuaFile file = p.Parse(@"
        .const ""print""
        .const ""Hello""
        getglobal 0 0
        loadk 1 1
        call 0 2 1
        return 0 1
        ");
            file.StripDebugInfo();
            string code = file.Compile();
            try
            {
                LuaFile f = Disassembler.Disassemble(code);
                System.IO.FileStream fs = new System.IO.FileStream("lasm.luac", System.IO.FileMode.Create);
                //foreach (char c in code)
                foreach (char c in f.Compile())
                    fs.WriteByte((byte)c);
                fs.Close();

                // Test chunk compiling/loading
                string s = f.Main.Compile(f);
                Chunk chnk = Disassembler.DisassembleChunk(s);

                // Test execution of code
                string s2 = f.Compile();
                LuaRuntime.Run(s2);
                LuaRuntime.Run(code);
                Console.WriteLine("The above line should say 'Hello'. If it doesn't there is an error.");
                Console.WriteLine(LASMDecompiler.Decompile(file));

            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            try
            {
                LuaFile lf = p.Parse("breakpoint 0 0 0");
                LuaRuntime.Run(lf.Compile());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("Test(s) done. Press any key to continue.");
            Console.ReadKey(true);
        }
Beispiel #27
0
            public void MediaPlayer_GetTags()
            {
                TagLib.File file = player.GetTags();
                song         = file.Tag.Title;
                album        = file.Tag.Album;
                author       = file.Tag.FirstPerformer;
                track        = file.Tag.Track + "/" + file.Tag.TrackCount;
                duration_sec = file.Properties.Duration.Seconds;
                duration_min = file.Properties.Duration.Minutes;
                try {
                    System.IO.File.Delete(configManager.ConfigPath + "cover.png");
                    System.IO.File.Delete(configManager.ConfigPath + "cover.jpg");
                    System.IO.File.Delete(configManager.ConfigPath + "cover.gif");
                } catch (Exception) {}

                foreach (TagLib.IPicture p in file.Tag.Pictures)
                {
                    Console.WriteLine("Picture:" + p.MimeType.ToString());
                    switch (p.MimeType.ToString())
                    {
                    case "image/jpg":
                        CoverFilename = "cover.jpg";
                        break;

                    case "image/gif":
                        CoverFilename = "cover.gif";
                        break;

                    case "image/png":
                        CoverFilename = "cover.png";
                        break;
                    }
                    System.IO.FileStream pic = System.IO.File.Create(configManager.ConfigPath + CoverFilename);
                    foreach (byte bit in p.Data.Data)
                    {
                        pic.WriteByte(bit);
                    }
                    pic.Close();
                }
                if (song == null)
                {
                    song = "[Desconocido]";
                }
                if (album == null)
                {
                    album = "[Desconocido]";
                }
                if (author == null)
                {
                    author = "[Desconocido]";
                }
            }
Beispiel #28
0
        public void RandomizeAndWrite(System.IO.FileStream stream, Random rand)
        {
            Index = rand.Next(ColorBytes.Count);

            for (int i = 0; i < addresses.GetLength(0); i++)
            {
                for (int j = 0; j < addresses.GetLength(1); j++)
                {
                    stream.Position = addresses[i, j];
                    stream.WriteByte(ColorBytes[Index][i, j]);
                }
            }
        }
Beispiel #29
0
        public static void SaveRAWImage(string aname, Image Image)
        {
            Bitmap bitmap = new Bitmap(Image);
            SizeF  bnd    = Image.PhysicalDimension;

            System.IO.FileStream fm = new System.IO.FileStream(aname + ".raw", System.IO.FileMode.Create);
            for (int x = 0; x < bnd.Width; x++)
            {
                for (int y = 0; y < bnd.Height; y++)
                {
                    Color c   = bitmap.GetPixel(x, y);
                    byte  fch = (byte)((c.R & 248) | c.G >> 5);
                    byte  fcl = (byte)((c.G & 28) << 3 | c.B >> 3);
                    fm.WriteByte(fch);
                    fm.WriteByte(fcl);
                }
            }
            fm.Close();
            fm = new System.IO.FileStream(aname + ".bmp", System.IO.FileMode.Create);
            Image.Save(fm, System.Drawing.Imaging.ImageFormat.Bmp);
            fm.Close();
        }
        public void CreateFromDirectory(string Dir, string Outfile)
        {
            string[] Filepaths = System.IO.Directory.GetFiles(Dir);

            ushort Filecount = (ushort)Filepaths.Length;
            uint   RequiredBytesForHeader = NumberUtils.Align(Filecount * 3u + 5u, 0x10u);             // 3 bytes per filesize + 3 bytes for an extra pointer to first file + 2 bytes for filecount
            var    Filestream             = new System.IO.FileStream(Outfile, System.IO.FileMode.Create);

            // header
            Filestream.Write(BitConverter.GetBytes(Filecount), 0, 2);
            Filestream.Write(NumberUtils.GetBytesForUInt24(RequiredBytesForHeader), 0, 3);
            uint TotalFilesize = RequiredBytesForHeader;

            foreach (string Path in Filepaths)
            {
                TotalFilesize += (uint)(new System.IO.FileInfo(Path).Length);
                Filestream.Write(NumberUtils.GetBytesForUInt24(TotalFilesize), 0, 3);
                TotalFilesize = TotalFilesize.Align(0x10u);
            }
            while (Filestream.Length < RequiredBytesForHeader)
            {
                Filestream.WriteByte(0x00);
            }

            // files
            foreach (string Path in Filepaths)
            {
                var File = new System.IO.FileStream(Path, System.IO.FileMode.Open);
                StreamUtils.CopyStream(File, Filestream, (int)File.Length);
                File.Close();
                while (Filestream.Length % 0x10 != 0)
                {
                    Filestream.WriteByte(0x00);
                }
            }

            Filestream.Close();
        }
Beispiel #31
0
 public bool Write(byte Value)
 {
     if (HFile == null)
     {
         return(false);
     }
     try {
         HFile.WriteByte(Value);
     } catch (System.Exception Excpt) {
         Err.Add(Excpt);
         return(false);
     }
     return(true);
 }
Beispiel #32
0
 public void writeFileStream(System.IO.FileStream fs)
 {
     byte[] bytearray = System.Text.Encoding.ASCII.GetBytes("blaat");
     try
     {
         bytearray = System.Text.Encoding.ASCII.GetBytes(filecontents);
     }
     catch (NullReferenceException) { Console.WriteLine("nothing to export"); }
     foreach (byte character in bytearray)
     {
         fs.WriteByte(character);
     }
     fs.Close();
 }
Beispiel #33
0
        static void Main(string[] args)
        {
            string folderName = @"c:\MyFolder";

            string pathString = System.IO.Path.Combine(folderName, "SubFolder");

            System.IO.Directory.CreateDirectory(pathString);

            string fileName = System.IO.Path.GetRandomFileName();

            pathString = System.IO.Path.Combine(pathString, fileName);

            Console.WriteLine("Path to my file: {0}\n", pathString);

            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;
            }

            // 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);
            }

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
Beispiel #34
0
        void HeartbeatThreadProc()
        {
            int triesremain = heartbeatretries;

            while (!badlocalhost && !stop)
            {
                try
                {
                    using (System.IO.FileStream fs = new System.IO.FileStream(heartbeattempfile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                    {
                        fs.WriteByte((byte)'T');
                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                        if ((int)'T' != fs.ReadByte())
                        {
                            throw new System.IO.IOException("Heartbeat thread data written was not read back correctly.");
                        }
                        fs.Close();
                    }
                    System.IO.File.Delete(heartbeattempfile);
                    triesremain = heartbeatretries; //reset

                    lock (clientstm)
                    {
                        clientstm.WriteByte((byte)'h');
                    }
#if FAILOVER_DEBUG
                    System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() + " heartbeat sent" + Environment.NewLine);
#endif

                    System.Threading.Thread.Sleep(heartbeattimeout);
                }
                catch (Exception e)
                {
#if FAILOVER_DEBUG
                    System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() +
                                                 " heartbeat thread error: " + e.ToString() + Environment.NewLine);
#endif
                    if (--triesremain <= 0)
                    {
#if FAILOVER_DEBUG
                        System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() +
                                                     " heartbeat thread error; tries=" + triesremain.ToString()
                                                     + " ;caused to break out: " + e.ToString() + Environment.NewLine);
#endif
                        break;
                    }
                }
            }
        }
        public static void uncompressFile(string inFile, string outFile)
        {
            int data = 0;
            int stopByte = -1;
            System.IO.FileStream outFileStream = new System.IO.FileStream(outFile, System.IO.FileMode.Create);
            ZInputStream inZStream = new ZInputStream(System.IO.File.Open(inFile, System.IO.FileMode.Open, System.IO.FileAccess.Read));
            while (stopByte != (data = inZStream.Read()))
            {
                byte _dataByte = (byte)data;
                outFileStream.WriteByte(_dataByte);
            }

            inZStream.Close();
            outFileStream.Close();
        }
 public void Initialize()
 {
     string libFolder = System.IO.Path.Combine(Environment.GetEnvironmentVariable("APPDATA") + "\\returnzork\\BackupV3\\PluginLib\\");
     if (!System.IO.Directory.Exists(libFolder + "\\Compression"))
         System.IO.Directory.CreateDirectory(libFolder + "\\Compression");
     if (!System.IO.File.Exists(libFolder + "\\Compression\\Ionic.Zip.dll"))
     {
         //TODO extract the file from resources
         using (System.IO.FileStream fs = new System.IO.FileStream(libFolder + "\\Compression\\Ionic.Zip.dll", System.IO.FileMode.CreateNew))
         {
             System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Compression_Plugin.Ionic.Zip.dll");
             for(int i = 0; i < stream.Length; i++)
                 fs.WriteByte((byte)stream.ReadByte());
         }
     }
     System.Reflection.Assembly.LoadFrom(Environment.GetEnvironmentVariable("APPDATA") + "\\returnzork\\BackupV3\\PluginLib\\Compression\\Ionic.Zip.dll");
 }
 public static void WriteResource(System.Reflection.Assembly targetAssembly, string resourceName, string filePath)
 {
     string[] resources = targetAssembly.GetManifestResourceNames();
     List<string> resoruceList = resources.ToList();
     foreach (string s in resoruceList)
     {
         using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(s))
         {
             using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filePath), resourceName), System.IO.FileMode.Create))
             {
                 for (int i = 0; i < stream.Length; i++)
                 {
                     fileStream.WriteByte((byte)stream.ReadByte());
                 }
                 fileStream.Close();
             }
         }
     }
 }
		private static void  WriteBytes(System.IO.FileInfo aFile, long size)
		{
			System.IO.Stream stream = null;
			try
			{
				stream = new System.IO.FileStream(aFile.FullName, System.IO.FileMode.Create);
				for (int i = 0; i < size; i++)
				{
					stream.WriteByte((byte) Byten(i));
				}
				stream.Flush();
			}
			finally
			{
				if (stream != null)
				{
					stream.Close();
				}
			}
		}
Beispiel #39
0
        void HeartbeatThreadProc()
        {
            int triesremain = heartbeatretries;
            while (!badlocalhost && !stop)
            {
                try
                {
                    using (System.IO.FileStream fs = new System.IO.FileStream(heartbeattempfile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None))
                    {
                        fs.WriteByte((byte)'T');
                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                        if ((int)'T' != fs.ReadByte())
                        {
                            throw new System.IO.IOException("Heartbeat thread data written was not read back correctly.");
                        }
                        fs.Close();
                    }
                    System.IO.File.Delete(heartbeattempfile);
                    triesremain = heartbeatretries; //reset                    

                    lock (clientstm)
                    {
                        clientstm.WriteByte((byte)'h');
                    }
#if FAILOVER_DEBUG
                    System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() + " heartbeat sent" + Environment.NewLine);
#endif

                    System.Threading.Thread.Sleep(heartbeattimeout);
                }
                catch(Exception e)
                {
#if FAILOVER_DEBUG
                    System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() + 
                        " heartbeat thread error: " + e.ToString() + Environment.NewLine);
#endif
                    if (--triesremain <= 0)
                    {
#if FAILOVER_DEBUG
                        System.IO.File.AppendAllText(@"c:\temp\vitalsreporter_A5B1E053-9A32-417b-8068-91A7CD5CDEAB.txt", DateTime.Now.ToString() +
                            " heartbeat thread error; tries=" + triesremain.ToString() 
                            + " ;caused to break out: " + e.ToString() + Environment.NewLine);
#endif
                        break;
                    }
                }
            }
        }
 public static void ExtractEmbeddedResource(string resourceLocation, string outputDir, List<string> files)
 {
     foreach (string file in files)
     {
         using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceLocation + @"." + file))
         {
             using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, file), System.IO.FileMode.Create))
             {
                 for (int i = 0; i < stream.Length; i++)
                 {
                     fileStream.WriteByte((byte)stream.ReadByte());
                 }
                 fileStream.Close();
             }
         }
     }
 }
Beispiel #41
0
        public void GenerateFiles( String Outdir )
        {
            System.IO.Directory.CreateDirectory( Outdir );
            for ( int i = 0; i < FileData.Count; ++i ) {
                RTDPfile r = FileData[i];
                uint start = r.Pointer;
                uint end = r.Pointer + r.Size;
                uint count = r.Size;

                string outfilename = r.Name;

                string outpath = System.IO.Path.Combine( Outdir, outfilename );
                var fs = new System.IO.FileStream( outpath, System.IO.FileMode.Create );

                for ( int j = 0; j < count; ++j ) {
                    fs.WriteByte( (byte)( File[start + j] ^ Xorbyte ) );
                }
                fs.Close();
            }

            // write filename order
            List<string> Filenames = new List<string>();
            foreach ( RTDPfile r in FileData ) {
                Filenames.Add( r.Name );
            }
            System.IO.File.WriteAllLines( Outdir + ".fileorder", Filenames.ToArray() );
        }
Beispiel #42
0
        public void CreateFromDirectory( string Dir, string Outfile, string[] FileOrder )
        {
            List<string> Filepaths = new List<string>();
            foreach ( string f in FileOrder ) {
                Filepaths.Add( System.IO.Path.Combine( Dir, f ) );
            }
            var Filestream = new System.IO.FileStream( Outfile, System.IO.FileMode.Create );

            uint RequiredBytesForHeader;
            uint Filecount = (uint)Filepaths.Count;
            uint TotalFilesize;
            Xorbyte = 0x55;
            //Xorbyte = 0x00;

            // 0x20 Header + 0x28 per file
            RequiredBytesForHeader = Util.Align( Filecount * 0x28u + 0x20u, 0x20u );

            TotalFilesize = RequiredBytesForHeader;
            foreach ( string Path in Filepaths ) {
                TotalFilesize += (uint)( new System.IO.FileInfo( Path ).Length );
                TotalFilesize = TotalFilesize.Align( 0x20u );
            }

            // header
            Filestream.WriteByte( (byte)'R' ); Filestream.WriteByte( (byte)'T' );
            Filestream.WriteByte( (byte)'D' ); Filestream.WriteByte( (byte)'P' );
            Filestream.Write( BitConverter.GetBytes( RequiredBytesForHeader ), 0, 4 );
            Filestream.Write( BitConverter.GetBytes( Filecount ), 0, 4 );
            Filestream.Write( BitConverter.GetBytes( TotalFilesize ), 0, 4 );
            Filestream.WriteByte( Xorbyte );
            Filestream.WriteByte( 0x28 ); Filestream.WriteByte( 0x25 );
            while ( Filestream.Length < 0x20 ) { Filestream.WriteByte( 0x00 ); }

            // header file info
            uint ptr = 0;
            foreach ( string Path in Filepaths ) {
                var fi = new System.IO.FileInfo( Path );
                uint size = (uint)( fi.Length );

                byte[] name = Encoding.ASCII.GetBytes( fi.Name );
                Filestream.Write( name, 0, Math.Min( 0x20, name.Length ) );
                for ( int i = name.Length; i < 0x20; ++i ) { Filestream.WriteByte( 0x00 ); }

                Filestream.Write( BitConverter.GetBytes( size ), 0, 4 );
                Filestream.Write( BitConverter.GetBytes( ptr ), 0, 4 );

                ptr = Util.Align( ptr + size, 0x20u );
            }
            while ( Filestream.Length < RequiredBytesForHeader ) { Filestream.WriteByte( 0x00 ); }

            // files
            foreach ( string Path in Filepaths ) {
                var File = new System.IO.FileStream( Path, System.IO.FileMode.Open );

                while ( true ) {
                    int b = File.ReadByte();
                    if ( b == -1 ) { break; }
                    Filestream.WriteByte( (byte)( b ^ Xorbyte ) );
                }

                File.Close();
                while ( Filestream.Length % 0x20 != 0 ) { Filestream.WriteByte( 0x00 ); }
            }

            Filestream.Close();
        }
Beispiel #43
0
 public static void DownloadFile(this File f, DriveService ds, string s, System.IO.StreamWriter w)
 {
     try
     {
         String path = System.IO.Path.Combine(s, f.OriginalFilename);
         if (System.IO.File.Exists(path))
         {
             if (!String.IsNullOrEmpty(f.OriginalFilename)) w.WriteDownloadStatus(f.OriginalFilename, 1);
             return;
         }
         if (!System.IO.Directory.Exists(s)) System.IO.Directory.CreateDirectory(s);
         byte[] arrBytes = ds.HttpClient.GetByteArrayAsync(f.DownloadUrl).Result;
         System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create);
         foreach (byte b in arrBytes) fs.WriteByte(b);
         fs.Close();
         w.WriteDownloadStatus(f.OriginalFilename);
     }
     catch (Exception e) { if (!String.IsNullOrEmpty(f.OriginalFilename)) w.WriteDownloadStatus(f.OriginalFilename, 1); } //Skip it
 }
Beispiel #44
0
 public static void SaveRAWImage(string aname, Image Image)
 {
     Bitmap bitmap = new Bitmap(Image);
     SizeF bnd = Image.PhysicalDimension;
     System.IO.FileStream fm = new System.IO.FileStream(aname+".raw", System.IO.FileMode.Create);
     for (int x = 0; x < bnd.Width; x++)
         for (int y=0;y<bnd.Height;y++)
         {
             Color c = bitmap.GetPixel(x, y);
             byte fch = (byte)((c.R & 248) | c.G >> 5);
             byte fcl = (byte)((c.G & 28) << 3 | c.B >> 3);
             fm.WriteByte(fch);
             fm.WriteByte(fcl);
         }
     fm.Close();
     fm = new System.IO.FileStream(aname + ".bmp", System.IO.FileMode.Create);
     Image.Save(fm, System.Drawing.Imaging.ImageFormat.Bmp);
     fm.Close();
 }
Beispiel #45
0
        public void Save(string MainFileName)
        {
            if (MainFileName.Substring(MainFileName.Length - 4) != ".scr")
                MainFileName = MainFileName + ".scr";
            string IDsFileName = MainFileName.Substring(0,MainFileName.Length-4) + ".ids";
            string DefsFileName = IDsFileName.Substring(0, IDsFileName.Length - 4) + ".h";
            System.IO.FileStream fs = new System.IO.FileStream(MainFileName, System.IO.FileMode.Create);
            System.Xml.XmlWriter fi = System.Xml.XmlWriter.Create(IDsFileName);
            System.IO.StreamWriter fd = new System.IO.StreamWriter(DefsFileName);

            //pnl.Image.Save(null, System.Drawing.Imaging.ImageFormat.Bmp);
            fi.WriteStartDocument();
            fi.WriteStartElement("Document");
            fi.WriteStartElement("Screen");
            fi.WriteElementString("SCREEN_Width", Width.ToString());
            fi.WriteElementString("SCREEN_Height", Height.ToString());
            fi.WriteElementString("SCREEN_BackColor", BackColor.ToString());
            fi.WriteElementString("SCREEN_FontColor", FontColor.ToString());
            fi.WriteElementString("SCREEN_ABorderColor", ActiveBorderColor.ToString());
            fi.WriteElementString("SCREEN_PBorderColor", PassiveBorderColor.ToString());
            if (pnl.Image != null)
            {
                string aname = String.Format("{0}\\{1}",System.IO.Path.GetDirectoryName(MainFileName),ScreenName);
                utftUtils.SaveRAWImage(aname, pnl.Image);
                fi.WriteElementString("Desctop", ScreenName);
            }
            fi.WriteEndElement();

            byte lbl = 0;
            byte btn = 0;
            foreach (KeyValuePair<string, TInterfaceElement> e in listitem)
            {
                if (e.Value.GetItemTypeNumber() == 3)
                e.Value.ID = lbl++;
                else e.Value.ID = btn++;
            }
            fs.WriteByte((byte)(13 + ScreenName.Length));// размер данных экрана
            utftUtils.Save2Bytes(fs, (UInt16)Width);
            utftUtils.Save2Bytes(fs, (UInt16)Height);

            UInt16 clr = utftUtils.GetUTFTColorBytes(BackColor);
            utftUtils.Save2Bytes(fs, clr);
            clr = utftUtils.GetUTFTColorBytes(FontColor);
            utftUtils.Save2Bytes(fs, clr);
            clr = utftUtils.GetUTFTColorBytes(ActiveBorderColor);
            utftUtils.Save2Bytes(fs, clr);
            clr = utftUtils.GetUTFTColorBytes(PassiveBorderColor);
            utftUtils.Save2Bytes(fs, clr);

            fs.WriteByte((byte)lbl);
            fs.WriteByte((byte)btn);
            fs.WriteByte((byte)ScreenName.Length);
            for (int i = 0; i < ScreenName.Length; i++)
                fs.WriteByte(Convert.ToByte(ScreenName[i]));
            fi.WriteStartElement("Elements");

            foreach (KeyValuePair<string, TInterfaceElement> e in listitem)
            {
                e.Value.Save(fs, fi);
                if (e.Value.ItemType!="Label")
                    fd.WriteLine(String.Format("#define {0} {1}", e.Value.ItemName, e.Value.ID));
            }

            fi.WriteEndElement();

            fi.WriteEndElement();
            fi.WriteEndDocument();

            fs.Close();
            fi.Close();
            fd.Close();

            fs.Dispose();
            fd.Dispose();
        }