Esempio n. 1
0
        /// <summary>
        /// ファイルからデータをロード
        /// </summary>
        public static void LoadData()
        {
            if(System.IO.File.Exists(@SAVEFILE)){
                using(var fs = System.IO.File.Open(@SAVEFILE,System.IO.FileMode.Open)){
                    // バイナリリーダ作成
                    var br = new System.IO.BinaryReader(fs);

                    // Read data
                    Global.isStageOpened[(int)StageID.Stage1] = br.ReadBoolean();
                    Global.isStageOpened[(int)StageID.Stage2] = br.ReadBoolean();
                    Global.isStageOpened[(int)StageID.Stage3] = br.ReadBoolean();

                    Global.characterLevel = br.ReadInt32();
                    Global.characterExp = br.ReadInt32();

                    br.Close();
                }
            }else{
                Global.isStageOpened[(int)StageID.Stage1] = true;
                Global.isStageOpened[(int)StageID.Stage2] = false;
                Global.isStageOpened[(int)StageID.Stage3] = false;

                Global.characterLevel = 1;
                Global.characterExp = 0;
            }
        }
Esempio n. 2
0
 public static MachineType GetDllMachineType(this string dllPath)
 {
     // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
     // Offset to PE header is always at 0x3C.
     // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
     // followed by a 2-byte machine type field (see the document above for the enum).
     //
     using (var fs = new System.IO.FileStream(dllPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
         using (var br = new System.IO.BinaryReader(fs)) {
             MachineType machineType = MachineType.IMAGE_FILE_MACHINE_UNKNOWN;
     //					bool isgood = false;
             try {
                 fs.Seek(0x3c, System.IO.SeekOrigin.Begin);
                 Int32 peOffset = br.ReadInt32();
                 fs.Seek(peOffset, System.IO.SeekOrigin.Begin);
                 UInt32 peHead = br.ReadUInt32();
                 if (peHead != 0x00004550)
                     // "PE\0\0", little-endian
                     throw new Exception("Can't find PE header");
                 machineType = (MachineType)br.ReadUInt16();
     //						isgood = true;
             }
             catch {
     //						isgood = false;
             }
             finally {
                 br.Close();
                 fs.Close();
             }
             return machineType;
         }
 }
        public override byte[] Read(long ID)
        {
            System.IO.FileStream fs = null;
            System.IO.BinaryReader	r = null;
            try {
                string path = BuildFilePath(ID);
                if (!System.IO.File.Exists(path))
                    return null;

                fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                r = new System.IO.BinaryReader(fs);

                int len = (int)fs.Length;
                byte [] b = r.ReadBytes(len);

                return b;
            }
            finally {
                if (r != null)
                    r.Close();

                if (fs != null)
                    fs.Close();
            }
        }
Esempio n. 4
0
        public static void Load()
        {
            IO.Log.Write("    Loading CampaingProgresss...");
            levelsCompleted.Clear();

            System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Saves/progress.lpg",
                System.IO.FileMode.Open));

            String s = "";
            int l = 0;
            while (br.PeekChar() > -1)
            {
                s = br.ReadString();
                l = br.ReadInt32();
                byte[] d = new byte[l];
                for (int j = 0; j < l; j++)
                {
                    d[j] = br.ReadByte();
                }
                levelsCompleted.Add(s, d);
            }

            br.Close();
            IO.Log.Write("    Loading complete");
        }
Esempio n. 5
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return _Buffer;
        }
Esempio n. 6
0
 public static byte[] FileToArray(string sFilePath)
 {
     System.IO.FileStream fs = new System.IO.FileStream(sFilePath,
         System.IO.FileMode.Open, System.IO.FileAccess.Read);
     System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
     Byte[] bytes = br.ReadBytes((Int32)fs.Length);
     br.Close();
     fs.Close();
     return bytes;
 }
Esempio n. 7
0
        public static System.Drawing.Size GetTGASize(string filename)
        {
            System.IO.FileStream f = System.IO.File.OpenRead(filename);

            System.IO.BinaryReader br = new System.IO.BinaryReader(f);

            tgaHeader header = new tgaHeader();
            header.Read(br);
            br.Close();

            return new System.Drawing.Size(header.ImageSpec.Width, header.ImageSpec.Height);
        }
Esempio n. 8
0
File: Main.cs Progetto: MetLob/tinke
        public System.Windows.Forms.Control Show_Info(sFile file)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.OpenRead(file.path));
            string ext = new String(br.ReadChars(4));
            br.Close();

            if (ext == "NFTR" || ext == "RTFN")
            {
                return new FontControl(pluginHost, NFTR.Read(file, pluginHost.Get_Language()));
            }

            return new System.Windows.Forms.Control();
        }
Esempio n. 9
0
        public byte[] GetImage(string filepath)
        {
            filepath = System.Web.Hosting.HostingEnvironment.MapPath(filepath);
            //string FolderPath = Server.MapPath("Images");
            System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);

            byte[] image = br.ReadBytes((int)fs.Length);

            br.Close();

            fs.Close();

            return image;

        }
Esempio n. 10
0
        public static void LoadFromBinanry(byte[] bytes)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            int length = br.ReadInt32();

            for (int i = 0; i < length; i++)
            {
                br.ReadByte();
            }

            int looplength = br.ReadInt32();

            for (int i = 0; i < looplength; i++)
            {
                Character dataCharacter = new Character();
                dataCharacter.ID       = br.ReadInt32();
                dataCharacter.Name     = br.ReadString();
                dataCharacter.Type     = br.ReadInt32();
                dataCharacter.Level    = br.ReadInt32();
                dataCharacter.Icon     = br.ReadString();
                dataCharacter.AT       = br.ReadInt32();
                dataCharacter.DF       = br.ReadInt32();
                dataCharacter.MAT      = br.ReadInt32();
                dataCharacter.MDF      = br.ReadInt32();
                dataCharacter.MP       = br.ReadInt32();
                dataCharacter.MV       = br.ReadInt32();
                dataCharacter.Control  = br.ReadInt32();
                dataCharacter.ArmAT    = br.ReadInt32();
                dataCharacter.ArmDF    = br.ReadInt32();
                dataCharacter.ArmLimit = br.ReadInt32();
                dataCharacter.ArmType  = br.ReadString();
                dataCharacter.Magic    = br.ReadString();
                dataCharacter.Res      = br.ReadString();
                if (_datas.ContainsKey(dataCharacter.ID))
                {
#if UNITY_EDITOR
                    UnityEditor.EditorApplication.isPaused = true;
#endif
                    throw new ArgumentException("数据有误,主键重复:" + dataCharacter.ID);
                }
                _datas.Add(dataCharacter.ID, dataCharacter);
            }
            br.Close();
            ms.Close();
        }
Esempio n. 11
0
        private void EmbeddedResourceHandler_ProcessRequest(object sender, Chromium.Event.CfxProcessRequestEventArgs e)
        {
            readResponseStreamOffset = 0;
            var request  = e.Request;
            var callback = e.Callback;

            var uri = new Uri(request.Url);

            requestUrl = request.Url;

            var fileName = string.Format("{0}{1}", uri.Authority, uri.AbsolutePath);

            requestFile = uri.AbsolutePath;

            var ass          = resourceAssembly;
            var resourcePath = string.Format("{0}.{1}", ass.GetName().Name, fileName.Replace('/', '.'));
            var resourceName = ass.GetManifestResourceNames().SingleOrDefault(p => p.Equals(resourcePath, StringComparison.CurrentCultureIgnoreCase));

            if (!string.IsNullOrEmpty(resourceName) && ass.GetManifestResourceInfo(resourceName) != null)
            {
                using (var reader = new System.IO.BinaryReader(ass.GetManifestResourceStream(resourceName)))
                {
                    var buff = reader.ReadBytes((int)reader.BaseStream.Length);

                    webResource = new WebResource(buff, MimeHelper.GetMimeType(System.IO.Path.GetExtension(fileName)));

                    reader.Close();

                    if (!browser.WebResources.ContainsKey(requestUrl))
                    {
                        browser.SetWebResource(requestUrl, webResource);
                    }
                }


                Console.WriteLine($"[加载]:\t{requestUrl}");
            }
            else
            {
                Console.WriteLine($"[未找到]:\t{requestUrl}");
            }


            callback.Continue();
            e.SetReturnValue(true);
        }
        private static byte[] GetResourceBytes(Assembly ass, string resourceName)
        {
            byte[] buff;
            using (var reader = new System.IO.BinaryReader(ass.GetManifestResourceStream(resourceName)))
            {
                buff = reader.ReadBytes((int)reader.BaseStream.Length);


                reader.Close();

                //if (WebResources.ContainsKey(requestUrl))
                //{
                //SetWebResource(requestUrl, webResource);
                //}
            }
            return(buff);
        }
Esempio n. 13
0
 private void ELFPather_Load(object sender, EventArgs e)
 {
     if (ELFOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         ELFFile = new System.IO.FileStream(ELFOpen.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
         if (ELFOpen.FilterIndex == 1)
         {
             StartUpOffset = PALStartUpOffset;
             StartUpSize   = PALStartUpSize;
             BootOffset    = PALBootOffset;
             BootSize      = PALBootSize;
         }
         else if (ELFOpen.FilterIndex == 2)
         {
             StartUpOffset = NTCSStartUpOffset;
             StartUpSize   = NTCSStartUpSize;
             BootOffset    = NTCSBootOffset;
             BootSize      = NTCSBootSize;
         }
         TextBox1.MaxLength = (int)StartUpSize;
         TextBox1.Text      = "";
         TextBox2.MaxLength = (int)BootSize;
         TextBox2.Text      = "";
         ELFReader          = new System.IO.BinaryReader(ELFFile);
         ELFFile.Position   = StartUpOffset;
         byte b;
         do
         {
             b              = ELFReader.ReadByte();
             TextBox1.Text += Strings.Chr(b);
         }while (~b == 0);
         ELFFile.Position = BootOffset;
         do
         {
             b              = ELFReader.ReadByte();
             TextBox2.Text += Strings.Chr(b);
         }while (~b == 0);
         ELFReader.Close();
         ELFFile.Close();
     }
     else
     {
         this.Close();
     }
 }
Esempio n. 14
0
        public static void LoadGram(string filename, ref int zoom, ref int w, ref int b, ref int amp, ref int filter)
        {
            int len = 0;

            System.IO.BinaryReader sw = new System.IO.BinaryReader(
                new System.IO.FileStream(filename, System.IO.FileMode.Open)
                );
            len    = sw.ReadInt32();
            zoom   = sw.ReadInt32();
            w      = sw.ReadInt32();
            b      = sw.ReadInt32();
            amp    = sw.ReadInt32();
            filter = sw.ReadInt32();


            while (sw.BaseStream.CanRead)
            {
                try
                {
                    List <double> list = new List <double>();
                    for (int i = 0; i < len; i++)
                    {
                        list.Add(sw.ReadDouble());
                    }
                    GramUtils.ArchiveData(list.ToArray <double>());
                }
                catch
                {
                    break;
                }
            }


            //System.IO.TextReader sw = new System.IO.StreamReader("d:\\text.txt");
            //this.RoundedArchive.Clear();
            //this.Archive.Clear();
            //this.NormalArchive.Clear();
            //while (true)
            //{
            //    LoadData(StrToDoubleAr(sw.ReadLine()));
            //}


            sw.Close();
        }
Esempio n. 15
0
        public static MainFileHeader GetFileHeader(string fileName)
        {
            MainFileHeader MainHeader;

            using (System.IO.FileStream shpStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
            {
                using (System.IO.BinaryReader shpReader = new System.IO.BinaryReader(shpStream))
                {
                    MainHeader = new MainFileHeader(shpReader.ReadBytes(ShapeConstants.MainHeaderLengthInBytes));

                    shpReader.Close();

                    shpStream.Close();
                }
            }

            return(MainHeader);
        }
Esempio n. 16
0
        public sFolder Unpack(sFile file)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.OpenRead(file.path));
            string type = new String(Encoding.ASCII.GetChars(br.ReadBytes(4)));

            br.Close();

            if (type == "ALAR")
            {
                return(new ALAR(pluginHost).Unpack(file));
            }
            else if (type == "DSCP")
            {
                return(new ALAR(pluginHost).Unpack(file));
            }

            return(new sFolder());
        }
Esempio n. 17
0
        public static void Solve()
        {
            Task("File14");

            var    s = new System.IO.BinaryReader(System.IO.File.Open(GetString(), System.IO.FileMode.Open));
            double res = 0;
            int    cnt = 0, lg = (int)s.BaseStream.Length, pos = 0;

            while (pos < lg)
            {
                res += s.ReadDouble();
                cnt += 1;
                pos += sizeof(double);
            }

            s.Close();
            Put(cnt == 0 ? 0 : res / cnt);
        }
Esempio n. 18
0
        private Effect LoadEffect(String file)
        {
            System.IO.BinaryReader reader = new System.IO.BinaryReader(TitleContainer.OpenStream(file));
            Effect effect = null;

            try
            {
                effect = new Effect(GraphicsDevice, reader.ReadBytes((int)reader.BaseStream.Length));
                Console.WriteLine("SUCCESSFULLY LOADED " + file);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                enableShaders = false;
            }
            reader.Close();
            return(effect);
        }
Esempio n. 19
0
        private void LocalResourceHandler_ProcessRequest(object sender, Chromium.Event.CfxProcessRequestEventArgs e)
        {
            readResponseStreamOffset = 0;
            var request  = e.Request;
            var callback = e.Callback;

            var uri = new Uri(request.Url);

            requestUrl = request.Url;
            var localPath = uri.LocalPath;

            if (localPath.StartsWith("/"))
            {
                localPath = string.Format(".{0}", localPath);
            }

            var fileName = System.IO.Path.GetFullPath(localPath);


            requestFile = request.Url;


            if (System.IO.File.Exists(fileName))
            {
                using (var stream = System.IO.File.OpenRead(fileName))
                    using (var reader = new System.IO.BinaryReader(stream))
                    {
                        var buff = reader.ReadBytes((int)reader.BaseStream.Length);
                        webResource = new WebResource(buff, MimeHelper.GetMimeType(System.IO.Path.GetExtension(fileName)));

                        reader.Close();
                        stream.Close();
                    }

                Console.WriteLine(string.Format("[加载]:\t{0}\t->\t{1}", requestUrl, fileName));
            }
            else
            {
                Console.WriteLine(string.Format("[未找到]:\t{0}", requestUrl));
            }

            callback.Continue();
            e.SetReturnValue(true);
        }
Esempio n. 20
0
        private void f17_ButtonReadKeyword_Click(object sender, EventArgs e)
        {
            Key = new byte[8][];
            for (int i = 0; i < 8; i++)
            {
                Key[i] = new byte[4];
            }
            int            byteNumber = 0;
            int            code;
            OpenFileDialog Load = new OpenFileDialog();

            if (Load.ShowDialog() == DialogResult.OK)
            {
                System.IO.BinaryReader reader = new System.IO.BinaryReader(System.IO.File.Open(Load.FileName, System.IO.FileMode.Open), Encoding.Default);
                int i = 0, j = 0;
                while ((code = reader.PeekChar()) > -1 && (byteNumber = i * 4 + j) < 32)
                {
                    Key[i][j] = reader.ReadByte();
                    j++;
                    if (j == 4)
                    {
                        j = 0; i++;
                    }
                }
                reader.Close();
                if (code == -1 && byteNumber == 31)
                {
                    f17_fieldKeyword.Text = "Source: " + Load.FileName;
                }
                else
                {
                    if (code == -1)
                    {
                        MessageBox.Show("Слишком короткий ключ в файле", "Ошибка");
                    }
                    if (byteNumber == 31)
                    {
                        MessageBox.Show("Слишком длинный ключ в файле", "Ошибка");
                    }
                    f17_fieldKeyword.Text = null;
                    Key = new byte[0][];
                }
            }
        }
Esempio n. 21
0
        public void DisconectMes()
        {
            try
            {
                Call2Discon = true;
                try
                {
                    if (stream == null)
                    {
                        stream = client.GetStream();
                    }
                    if (writer == null)
                    {
                        writer = new System.IO.BinaryWriter(stream);
                    }
                    writer.Write("DisconnectZ Вы отключены от сервера");
                    writer.Close();
                }
                catch (Exception)
                {
                }

                FS.StatusBox.Text += "\r\n(" + DateTime.Now.ToString() + ") Завершил соединение: " + MYIpClient;
                if (stream != null)
                {
                    stream.Close();
                    stream = null;
                }
                if (client != null)
                {
                    client.Close();
                    client = null;
                }
                if (reader != null)
                {
                    reader.Close();
                    reader = null;
                }
            }
            catch (Exception ex)
            {
                FS.StatusBox.Text += "\r\n(" + DateTime.Now.ToString() + ") Ошибка: " + ex.ToString() + "\r\n Место ошибки: Метод DisconectMes";
            }
        }
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ValidateCard())
                {
                    var dialog = new SaveFileDialog();

                    dialog.Filter       = "PDF Files (*.pdf)|*.pdf";
                    dialog.DefaultExt   = "pdf";
                    dialog.AddExtension = true;
                    if (dialog.ShowDialog().GetValueOrDefault() == true)
                    {
                        using (var fs = new System.IO.FileStream(DetailsObj.DocumentPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            using (var sr = new System.IO.BinaryReader(fs))
                            {
                                var fs1 = new System.IO.FileStream(dialog.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                                var sw  = new System.IO.BinaryWriter(fs1);
                                sw.Write(sr.ReadBytes((int)fs.Length - 1));

                                sw.Close();
                                fs1.Close();
                                sr.Close();
                                fs.Close();
                            }
                        }
                        MessageBox.Show("File Downloaded SuccessFully!");
                    }
                }
                else
                {
                    MessageBox.Show("Enter Your Credit Card Details!!!");
                }
            }
            catch (ELibException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 23
0
        private void importTilesetBtn_Click(object sender, EventArgs e)
        {
            getFiles();

            if (GFXFile == null)
            {
                return;
            }
            if (PalFile == null)
            {
                return;
            }
            if (LayoutFile == null)
            {
                return;
            }

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter          = LanguageManager.Get("Filters", "background");
            ofd.CheckFileExists = true;

            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            System.IO.BinaryReader br = new System.IO.BinaryReader(
                new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read));
            string header = br.ReadString();

            if (header != fileHeader)
            {
                MessageBox.Show(
                    LanguageManager.Get("NSMBLevel", "InvalidFile"),
                    LanguageManager.Get("NSMBLevel", "Unreadable"),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            readFileContents(GFXFile, br);
            readFileContents(PalFile, br);
            readFileContents(LayoutFile, br);
            br.Close();
        }
Esempio n. 24
0
        public async Task <ActionResult> Register(RegisterViewModel model, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                //var user = new ApplicationUser { UserName = model.UserName,LastName = model.LastName,FirstName = model.FirstName,UserImage = model.UserImage, Email = model.Email };
                var user = model.GetUser();
                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new File
                    {
                        FileName    = System.IO.Path.GetFileName(upload.FileName),
                        FileType    = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                        reader.Close();
                    }
                    user.Files = new List <File> {
                        avatar
                    };
                }
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Account"));
                }
                //AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 25
0
        /// <summary>
        /// Reads the catalog from the disk.
        /// </summary>
        public static CCatalogNode ReadCatalog(string Filename)
        {
            // Create the root node
            CCatalogNode Node = new CCatalogNode();

            // Open the file
            System.IO.BinaryReader file = new System.IO.BinaryReader(new System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

            // Read backup file name
            file.ReadString();

            // Read nodes
            Node.ReadNode(file);

            // Close the file
            file.Close();

            return(Node);
        }
Esempio n. 26
0
        /// <summary>
        /// CML: Created shared binary reader to ensure the file is being read correctly.
        /// </summary>
        /// <param name="File"></param>
        /// <returns>An array containing data.  Array is sized for the data from the file.</returns>
        public static byte[] readBinaryFile(System.IO.FileInfo File)
        {
            byte[] data = new byte[(int)File.Length];
            System.IO.BinaryReader fis = null;
            try
            {
                fis = new System.IO.BinaryReader(new System.IO.FileStream(File.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                fis.Read(data, 0, data.Length);
            }
            finally
            {
                if (fis != null)
                {
                    fis.Close();
                }
            }

            return(data);
        }
Esempio n. 27
0
        private byte[] LoadAllFile(RName dll)
        {
            try
            {
                var dllFile = new System.IO.FileStream(dll.Address, System.IO.FileMode.Open);

                var binReader = new System.IO.BinaryReader(dllFile);
                var bBuffer   = new byte[dllFile.Length];
                binReader.Read(bBuffer, 0, (int)dllFile.Length);
                binReader.Close();
                dllFile.Close();
                return(bBuffer);
            }
            catch (Exception ex)
            {
                Profiler.Log.WriteException(ex);
                return(null);
            }
        }
Esempio n. 28
0
 //=====================================
 //          static member
 //-------------------------------------
 /// <summary>
 /// 指定されたファイルの内容を、バイナリで全て抜き出します。
 /// </summary>
 /// <param name="filename">ファイル名を指定します。</param>
 /// <returns>byte[] にファイルの内容を格納して返します。</returns>
 public static byte[] WholeFileInBinary(string filename)
 {
     //バイナリデータの読込
     if (!System.IO.File.Exists(filename))
     {
         System.Console.Write("指定したファイルは存在しません\n");
         return(new byte[] {});
     }
     byte[] rtn;
     try{
         System.IO.FileStream   fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
         System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
         int filelen = (int)(new System.IO.FileInfo(filename).Length);
         rtn = br.ReadBytes(filelen);
         br.Close();
         fs.Close();
     }catch { throw; }
     return(rtn);
 }
Esempio n. 29
0
        public static bool CopyBinaryFile(string srcfilename, string destfilename)
        {
            if (System.IO.File.Exists(srcfilename) == false)
            {
                Debug.Log("Could not find The Source file " + srcfilename);
                return(false);
            }
            if (System.IO.File.Exists(destfilename) == true)
            {
                string message = "Source File: " + destfilename + " 已经存在!!! 是否选择覆盖";
                if (!EditorUtility.DisplayDialog("警告!!!", message, "是的", "取消"))
                {
                    return(false);
                }
            }

            System.IO.Stream s1 = System.IO.File.Open(srcfilename, System.IO.FileMode.Open);
            System.IO.Stream s2 = System.IO.File.Open(destfilename, System.IO.FileMode.Create);

            System.IO.BinaryReader f1 = new System.IO.BinaryReader(s1);
            System.IO.BinaryWriter f2 = new System.IO.BinaryWriter(s2);

            while (true)
            {
                byte[] buf = new byte[10240];
                int    sz  = f1.Read(buf, 0, 10240);

                if (sz <= 0)
                {
                    break;
                }

                f2.Write(buf, 0, sz);

                if (sz < 10240)
                {
                    break; // eof reached
                }
            }
            f1.Close();
            f2.Close();
            return(true);
        }
Esempio n. 30
0
        private static bool loadPacketDump(string file)
        {
            try
            {
                System.IO.FileStream   fs = new System.IO.FileStream(file, System.IO.FileMode.Open);
                System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                UInt32 magic = br.ReadUInt32();
                if (magic != 0x23c0ffee)
                {
                    System.Console.WriteLine("This is not a valid packet dump");
                    return(false);
                }
                UInt32 numTypes = br.ReadUInt32();
                for (int i = 0; i < numTypes; i++)
                {
                    deserialize_packet(br, null);
                }

                UInt32 magic2 = br.ReadUInt32();
                if (magic2 != 0x12021984)
                {
                    System.Console.WriteLine("This is not a valid packet dump");
                    return(false);
                }
                UInt32 numDefines = br.ReadUInt32();
                for (int i = 0; i < numDefines; i++)
                {
                    Define d = new Define();
                    d.abName  = readString(br);
                    d.abValue = readString(br);
                    defineList.Add(d);
                }

                br.Close();
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 31
0
        /// <summary>
        /// Loads a file consisting of 256x256 floats and imports it as an array into the map.
        /// </summary>
        /// <remarks>TODO: Move this to libTerrain itself</remarks>
        /// <param name="filename">The filename of the float array to import</param>
        public void loadFromFileF32(string filename)
        {
            System.IO.FileInfo     file = new System.IO.FileInfo(filename);
            System.IO.FileStream   s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
            int x, y;

            for (x = 0; x < w; x++)
            {
                for (y = 0; y < h; y++)
                {
                    heightmap.map[x, y] = (double)bs.ReadSingle();
                }
            }

            bs.Close();
            s.Close();

            tainted++;
        }
Esempio n. 32
0
 public static byte[] FileToByteArray(string _FileName)
 {
     byte[] _Buffer = null;
     try
     {
         // Open file for reading
         System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
         System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
         long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
         _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
         _FileStream.Close();
         _FileStream.Dispose();
         _BinaryReader.Close();
     }
     catch
     {
         //
     }
     return _Buffer;
 }
Esempio n. 33
0
        //--------------------------------------------------------------------------------------



        ///
        ///   对任意类型的文件进行base64加码
        ///
        ///   文件的路径和文件名
        ///   对文件进行base64编码后的字符串
        public static string   encodingforfile(string filename)
        {
            System.IO.FileStream   fs = System.IO.File.OpenRead(filename);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);



            /*system.byte[]   b=new   system.byte[fs.length];
             * fs.read(b,0,convert.toint32(fs.length));*/



            string base64string = Convert.ToBase64String(br.ReadBytes((int)fs.Length));



            br.Close();
            fs.Close();
            return(base64string);
        }
Esempio n. 34
0
        protected SCOR.AScorItem GetGuiElement(string name, byte[] data)
        {
            SCOR.AScorItem ret = null;
            if (GuiElements.ContainsKey(name))
            {
                ret = System.Activator.CreateInstance(GuiElements[name], new object[] { this }) as SCOR.AScorItem;
            }
            if (ret == null)
            {
                ret = new SCOR.ScoreItemDefault(this);
            }
            if (data != null)
            {
                System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.MemoryStream(data));
                ret.SetData(name, br);
                br.Close();
            }

            return(ret);
        }
Esempio n. 35
0
            private static BufferPacketData GetBindAck(ArraySegment<byte> array_segment)
            {
                BufferPacketData packet = new BufferPacketData();

                System.IO.MemoryStream ms = new System.IO.MemoryStream(array_segment.Array, array_segment.Offset, array_segment.Count, false);
                System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

                packet.PacketID = br.ReadUInt32();
                packet.DataSize = br.ReadUInt32();
                packet.Index = br.ReadUInt32();
                packet.Sequence = br.ReadUInt16();
                var buffer_size = (int)packet.DataSize - header_size;
                packet.BufferData = new byte[buffer_size];
                packet.BufferData = br.ReadBytes(buffer_size);

                br.Close();
                ms.Close();

                return packet;
            }
Esempio n. 36
0
        private void LoadData(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                try
                {
                    Encoding               windows1252Encoding = Encoding.GetEncoding(1252);
                    System.IO.FileStream   inStream            = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    System.IO.BinaryReader inFile = new System.IO.BinaryReader(inStream, windows1252Encoding);

                    int version = inFile.ReadInt32();

                    BackfieldLeaderBirthday.Day   = inFile.ReadInt32();
                    BackfieldLeaderBirthday.Month = inFile.ReadInt32();
                    mBackfieldWeight = inFile.ReadDouble();

                    DefensiveFrontLeaderBirthday.Day   = inFile.ReadInt32();
                    DefensiveFrontLeaderBirthday.Month = inFile.ReadInt32();
                    mDefensiveFrontWeight = inFile.ReadDouble();

                    OffensiveLineLeaderBirthday.Day   = inFile.ReadInt32();
                    OffensiveLineLeaderBirthday.Month = inFile.ReadInt32();
                    mOffensiveLineWeight = inFile.ReadDouble();

                    ReceiversLeaderBirthday.Day   = inFile.ReadInt32();
                    ReceiversLeaderBirthday.Month = inFile.ReadInt32();
                    mReceiversWeight = inFile.ReadDouble();

                    SecondaryLeaderBirthday.Day   = inFile.ReadInt32();
                    SecondaryLeaderBirthday.Month = inFile.ReadInt32();
                    mSecondaryWeight = inFile.ReadDouble();

                    inFile.Close();
                }
                catch (System.IO.IOException e)
                {
                    MessageBox.Show("Error reading '" + filePath + "': " + e.ToString(), "Error Loading Chemistry File",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 37
0
        public void LeCadastroDoArquivo()
        {
            System.IO.BinaryReader leitor = null;
            Aluno a;
            int   n;

            this.lista = new System.Collections.Generic.List <Aluno>();

            try
            {
                leitor = new System.IO.BinaryReader(new System.IO.FileStream("alunos.dat", System.IO.FileMode.Open));

                n = leitor.ReadInt32();
                for (int i = 0; i < n; i++)
                {
                    a       = new Aluno();
                    a.nome  = leitor.ReadString();
                    a.idade = leitor.ReadInt32();
                    a.sexo  = leitor.ReadChar();

                    this.lista.Add(a);
                }
            }
            catch (System.IO.FileNotFoundException)
            {
                Console.WriteLine("AVISO! Arquivo alunos.dat não foi encontrado. Cadastro começará vazio.");
                Console.ReadKey();
            }
            catch (System.Exception exc)
            {
                Console.WriteLine("ERRO! " + exc.Message);
                Console.ReadKey();
            }
            finally
            {
                if (leitor != null)
                {
                    leitor.Close();
                }
            }
        }
        void RestoreOldClassSpecials(SaveTree saveTree, Races classicTransformedRace)
        {
            try
            {
                // Get old class record
                SaveTreeBaseRecord oldClassRecord = saveTree.FindRecord(RecordTypes.OldClass);
                if (oldClassRecord == null)
                {
                    return;
                }

                // Read old class data
                System.IO.MemoryStream stream = new System.IO.MemoryStream(oldClassRecord.RecordData);
                System.IO.BinaryReader reader = new System.IO.BinaryReader(stream);
                ClassFile classFile           = new ClassFile();
                classFile.Load(reader);
                reader.Close();

                // Restore any specials set by transformed race
                if (classicTransformedRace == Races.Vampire)
                {
                    // Restore pre-vampire specials
                    characterDocument.career.DamageFromSunlight   = classFile.Career.DamageFromSunlight;
                    characterDocument.career.DamageFromHolyPlaces = classFile.Career.DamageFromHolyPlaces;
                    characterDocument.career.Paralysis            = classFile.Career.Paralysis;
                    characterDocument.career.Disease = classFile.Career.Disease;
                }
                else if (classicTransformedRace == Races.Werewolf)
                {
                    // TODO: Restore pre-werewolf specials
                }
                else if (classicTransformedRace == Races.Wereboar)
                {
                    // TODO: Restore pre-wereboar specials
                }
            }
            catch (Exception ex)
            {
                Debug.LogErrorFormat("Could not restore old class specials for vamp/were import. Error: '{0}'", ex.Message);
            }
        }
        private static List <MnistImage> ReadMnistBase(string imageFilePath, string labelFilePath)
        {
            List <MnistImage> images = new List <MnistImage>();

            System.IO.FileStream   fsImage = new System.IO.FileStream(imageFilePath, System.IO.FileMode.Open);
            System.IO.FileStream   fsLabel = new System.IO.FileStream(labelFilePath, System.IO.FileMode.Open);
            System.IO.BinaryReader brImage = new System.IO.BinaryReader(fsImage);
            System.IO.BinaryReader brLabel = new System.IO.BinaryReader(fsLabel);

            int magic1     = ReverseByte(brImage.ReadInt32());
            int imageCount = ReverseByte(brImage.ReadInt32());
            int rowsCount  = ReverseByte(brImage.ReadInt32());
            int colsCount  = ReverseByte(brImage.ReadInt32());

            int magic2     = ReverseByte(brLabel.ReadInt32());
            int labesCount = ReverseByte(brLabel.ReadInt32());

            for (int n = 0; n < imageCount; n++)
            {
                List <List <byte> > bytes = new List <List <byte> >();
                for (int i = 0; i < rowsCount; i++)
                {
                    List <byte> col = new List <byte>();
                    for (int j = 0; j < colsCount; j++)
                    {
                        col.Add(brImage.ReadByte());
                    }
                    bytes.Add(col);
                }
                byte       label = brLabel.ReadByte();
                MnistImage img   = new MnistImage(rowsCount, colsCount, bytes, label);
                images.Add(img);
            }

            fsImage.Close();
            fsLabel.Close();
            brImage.Close();
            brLabel.Close();

            return(images);
        }
Esempio n. 40
0
File: Main.cs Progetto: MetLob/tinke
        public Control Show_Info(sFile file)
        {
            System.IO.BinaryReader br = new System.IO.BinaryReader(System.IO.File.OpenRead(file.path));
            string ext = "";
            try { ext = new String(br.ReadChars(4)); }
            catch { }
            br.Close();

            if (file.name.ToUpper().EndsWith(".TGA"))
                return new TGA(pluginHost, file.path).Show_Info();
            else if (file.name.ToUpper().EndsWith(".JPG"))
                return new JPG(pluginHost, file.path).Show_Info();
            else if (file.name.ToUpper().EndsWith(".PNG"))
                return new PNG(pluginHost, file.path).Show_Info();
            else if (file.name.ToUpper().EndsWith(".WAV") || ext == "RIFF")
                return new WAV(pluginHost, file.path).Show_Info();
            else if (file.name.ToUpper().EndsWith(".BMP"))
                return new BMP(pluginHost, file.path).Show_Info();

            return new Control();
        }
        static int _m_Close(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.BinaryReader gen_to_be_invoked = (System.IO.BinaryReader)translator.FastGetCSObj(L, 1);



                {
                    gen_to_be_invoked.Close(  );



                    return(0);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
Esempio n. 42
0
        public void Start(string InputFilename, string OutputFilename, UInt64 Key, DESMode.DESMode Mode, bool Decode)
        {
            using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(System.IO.File.Open(InputFilename, System.IO.FileMode.Open)))
            {
                using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(System.IO.File.Open(OutputFilename, System.IO.FileMode.OpenOrCreate)))
                {
                    const int MaxSize = 1048576;
                    int n = 0;
                    byte[] buffer = new byte[MaxSize];
                    int size = 0;
                    int k = 0;
                    UInt64 DESResult = 0;

                    while ((n = Reader.Read(buffer, 0, MaxSize)) > 0)
                    {
                        k = 0;
                        while (n > 0)
                        {
                            if ((n / 8) > 0)
                                size = 8;
                            else
                                size = n;
                            byte[] tempArray = new byte[size];
                            for (int i = 0; i != size; ++i, ++k)
                                tempArray[i] = buffer[k];

                            if (!Decode)
                                DESResult = Mode.EncodeBlock(GetUIntFromByteArray(tempArray), Key);
                            else
                                DESResult = Mode.DecodeBlock(GetUIntFromByteArray(tempArray), Key);
                            Writer.Write(GetByteArrayFromUInt(DESResult, size), 0, size);

                            n -= 8;
                        }
                    }
                    Writer.Close();
                }
                Reader.Close();
            }
        }
Esempio n. 43
0
            /// <summary>
            /// Function to get byte array from a file
            /// </summary>
            /// <param name="fileName">File name to get byte array</param>
            /// <returns>Byte Array</returns>
            public static byte[] FileToByteArray(string fileName)
            {
                byte[] buffer;

                // Open file for reading
                var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                using (var binaryReader = new System.IO.BinaryReader(fileStream))
                {
                    var totalBytes = new System.IO.FileInfo(fileName).Length;

                    // read entire file into buffer
                    buffer = binaryReader.ReadBytes((Int32)totalBytes);

                    // close file reader
                    fileStream.Close();
                    fileStream.Dispose();
                    binaryReader.Close();
                }

                return buffer;
            }
		public static void  Main(System.String[] args)
		{
			PorterStemmer s = new PorterStemmer();
			
			for (int i = 0; i < args.Length; i++)
			{
				try
				{
					System.IO.BinaryReader in_Renamed = new System.IO.BinaryReader(System.IO.File.Open(args[i], System.IO.FileMode.Open, System.IO.FileAccess.Read));
					byte[] buffer = new byte[1024];
					int bufferLen, offset, ch;
					
					bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
					offset = 0;
					s.Reset();
					
					while (true)
					{
						if (offset < bufferLen)
							ch = buffer[offset++];
						else
						{
							bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
							offset = 0;
							if (bufferLen <= 0)
								ch = - 1;
							else
								ch = buffer[offset++];
						}
						
						if (System.Char.IsLetter((char) ch))
						{
							s.Add(System.Char.ToLower((char) ch));
						}
						else
						{
							s.Stem();
							System.Console.Out.Write(s.ToString());
							s.Reset();
							if (ch < 0)
								break;
							else
							{
								System.Console.Out.Write((char) ch);
							}
						}
					}
					
					in_Renamed.Close();
				}
				catch (System.IO.IOException )
				{
					System.Console.Out.WriteLine("error reading " + args[i]);
				}
			}
		}
		/// <summary>Renames an existing file in the directory. </summary>
		public override void  RenameFile(System.String from, System.String to)
		{
			lock (this)
			{
				System.IO.FileInfo old = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, from));
				System.IO.FileInfo nu = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, to));
				
				/* This is not atomic.  If the program crashes between the call to
				delete() and the call to renameTo() then we're screwed, but I've
				been unable to figure out how else to do this... */
				
				bool tmpBool;
				if (System.IO.File.Exists(nu.FullName))
					tmpBool = true;
				else
					tmpBool = System.IO.Directory.Exists(nu.FullName);
				if (tmpBool)
				{
					bool tmpBool2;
					if (System.IO.File.Exists(nu.FullName))
					{
						System.IO.File.Delete(nu.FullName);
						tmpBool2 = true;
					}
					else if (System.IO.Directory.Exists(nu.FullName))
					{
						System.IO.Directory.Delete(nu.FullName);
						tmpBool2 = true;
					}
					else
						tmpBool2 = false;
					if (!tmpBool2)
						throw new System.IO.IOException("Cannot delete " + to);
				}
				
				// Rename the old file to the new one. Unfortunately, the renameTo()
				// method does not work reliably under some JVMs.  Therefore, if the
				// rename fails, we manually rename by copying the old file to the new one
                try
                {
                    old.MoveTo(nu.FullName);
                }
                catch (System.Exception ex)
                {
                    System.IO.BinaryReader in_Renamed = null;
                    System.IO.Stream out_Renamed = null;
                    try
                    {
                        in_Renamed = new System.IO.BinaryReader(System.IO.File.Open(old.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        out_Renamed = new System.IO.FileStream(nu.FullName, System.IO.FileMode.Create);
                        // see if the buffer needs to be initialized. Initialization is
                        // only done on-demand since many VM's will never run into the renameTo
                        // bug and hence shouldn't waste 1K of mem for no reason.
                        if (buffer == null)
                        {
                            buffer = new byte[1024];
                        }
                        int len;
                        len = in_Renamed.Read(buffer, 0, buffer.Length);
                        out_Renamed.Write(buffer, 0, len);
						
                        // delete the old file.
                        bool tmpBool3;
                        if (System.IO.File.Exists(old.FullName))
                        {
                            System.IO.File.Delete(old.FullName);
                            tmpBool3 = true;
                        }
                        else if (System.IO.Directory.Exists(old.FullName))
                        {
                            System.IO.Directory.Delete(old.FullName);
                            tmpBool3 = true;
                        }
                        else
                            tmpBool3 = false;
                        bool generatedAux = tmpBool3;
                    }
                    catch (System.IO.IOException e)
                    {
                        throw new System.IO.IOException("Cannot rename " + from + " to " + to);
                    }
                    finally
                    {
                        if (in_Renamed != null)
                        {
                            try
                            {
                                in_Renamed.Close();
                            }
                            catch (System.IO.IOException e)
                            {
                                throw new System.SystemException("Cannot close input stream: " + e.Message);
                            }
                        }
                        if (out_Renamed != null)
                        {
                            try
                            {
                                out_Renamed.Close();
                            }
                            catch (System.IO.IOException e)
                            {
                                throw new System.SystemException("Cannot close output stream: " + e.Message);
                            }
                        }
                    }
                }
			}
		}
Esempio n. 46
0
        /// <summary>
        /// Loads a file consisting of 256x256 doubles and imports it as an array into the map.
        /// </summary>
        /// <remarks>TODO: Move this to libTerrain itself</remarks>
        /// <param name="filename">The filename of the double array to import</param>
        public void loadFromFileF64(string filename)
        {
            System.IO.FileInfo file = new System.IO.FileInfo(filename);
            System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
            int x, y;
            for (x = 0; x < w; x++)
            {
                for (y = 0; y < h; y++)
                {
                    heightmap.map[x, y] = bs.ReadDouble();
                }
            }

            bs.Close();
            s.Close();

            tainted++;
        }
Esempio n. 47
0
        /// <summary>
        /// Criptografa um arquivo em outro arquivo.
        /// </summary>
        /// <param name="p_inputfilename">Nome do arquivo de entrada.</param>
        /// <param name="p_outputfilename">Nome do arquivo de saída.</param>
        /// <param name="p_chunksize">Tamanho do bloco em bytes.</param>
        public void EncryptFile(string p_inputfilename, string p_outputfilename, int p_chunksize)
        {
            System.IO.FileStream v_inputfile, v_outputfile;
            System.IO.BinaryReader v_reader;
            System.IO.StreamWriter v_writer;
            int v_chunksize, v_bytestoread;
            byte[] v_chunk;
            string v_cryptedchunk;

            // tamanho em bytes da porcao do arquivo que corresponderah a uma linha no arquivo criptografado
            v_chunksize = p_chunksize;

            try
            {
                v_inputfile = new System.IO.FileStream(p_inputfilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                v_outputfile = new System.IO.FileStream(p_outputfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                v_reader = new System.IO.BinaryReader(v_inputfile);
                v_writer = new System.IO.StreamWriter(v_outputfile);

                v_bytestoread = (int) v_inputfile.Length;

                while (v_bytestoread > 0)
                {
                    v_chunk = v_reader.ReadBytes(v_chunksize);

                    // criptografando
                    v_cryptedchunk = this.Encrypt(v_chunk);

                    // escrevendo linha criptografada
                    v_writer.WriteLine(v_cryptedchunk);

                    v_bytestoread -= v_chunksize;
                }

                v_reader.Close();
                v_writer.Flush();
                v_writer.Close();
            }
            catch (System.IO.IOException e)
            {
                throw new Spartacus.Utils.Exception(e);
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Utils.Exception(e);
            }
        }
Esempio n. 48
0
        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型  ---说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
        /// </summary>
        /// <param name="hpf"></param>
        /// <param name="code">文件的前2个字节转化出来的小数</param>
        /// <returns></returns>
        public bool CheckUploadByTwoByte(HttpPostedFile hpf, Int64 code)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //
            //if (fileclass == code.ToString())
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
            return (fileclass == code.ToString());
        }
Esempio n. 49
0
 /// <summary>
 /// Loads a quadtree from a file
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public static QuadTree FromFile(string filename)
 {
     System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open,System.IO.FileAccess.Read);
     System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
     if (br.ReadDouble() != INDEXFILEVERSION) //Check fileindex version
     {
         fs.Close();
         fs.Dispose();
         throw new ObsoleteFileFormatException("Invalid index file version. Please rebuild the spatial index by either deleting the index");
     }
     QuadTree node = ReadNode(0, ref br);
     br.Close();
     fs.Close();
     return node;
 }
Esempio n. 50
0
        public override void GetData()
        {
            System.IO.FileStream file = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            System.IO.BinaryReader reader = new System.IO.BinaryReader(file);

            reader.BaseStream.Seek(filePointer, System.IO.SeekOrigin.Begin);

            byte[] fileData = reader.ReadBytes(32);
            filePointer += 32;

            Append(fileData);
            reader.Close();
            file.Close();
        }
Esempio n. 51
0
 /// <summary>
 /// 真正判断文件类型的关键函数(不太准确,比如txt获取到的值都不一样)
 /// </summary>
 /// <param name="hifile"></param>
 /// <returns></returns>
 public static string GetFileTrueType(System.Web.HttpPostedFile postedFile)
 {
     //System.IO.FileStream fs = new System.IO.FileStream(strPhysicsPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
     System.IO.Stream fs = postedFile.InputStream;
     System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
     string fileclass = "";
     byte buffer;
     try
     {
         buffer = r.ReadByte();
         fileclass = buffer.ToString();
         buffer = r.ReadByte();
         fileclass += buffer.ToString();
     }
     catch { }
     r.Close();
     fs.Close();
     /*文件扩展名说明
      *7173        gif
      *255216      jpg
      *13780       png
      *6677        bmp
      *239187      txt,aspx,asp,sql
      *208207      xls.doc.ppt
      *6063        xml
      *6033        htm,html
      *4742        js
      *8075        xlsx,zip,pptx,mmap,zip
      *8297        rar
      *01          accdb,mdb
      *7790        exe,dll
      *5666        psd
      *255254      rdp
      *10056       bt种子
      *64101       bat
      */
     if (fileclass == "255216")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
     {
         return "jpg";
     }
     else if (fileclass == "7173")
     {
         return "gif";
     }
     else if (fileclass == "6677")
     {
         return "bmp";
     }
     else if (fileclass == "13780")
     {
         return "png";
     }
     else if (fileclass == "7790")
     {
         return "exe";
     }
     else if (fileclass == "8297")
     {
         return "rar/zip";
     }
     else if (fileclass == "208207")
     {
         return "doc/xls";
     }
     else if (fileclass == "8075")
     {
         return "docx/xlsx";
     }
     else if (fileclass == "5155")
     {
         return "txt";
     }
     else if (fileclass == "6787")
     {
         return "swf";
     }
     else
     {
         return "";
     }
 }
Esempio n. 52
0
        /// <summary>
        /// Reads the name of the backup file used to create the catalog.
        /// </summary>
        public static string ReadBackupFilename(string Filename)
        {
            // Open the file
            System.IO.BinaryReader file = new System.IO.BinaryReader(new System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read));

            // Read backup file name
            string bkfname = file.ReadString();

            // Close the file
            file.Close();

            return bkfname;
        }
Esempio n. 53
0
 void CreateShader()
 {
     byte[] buffer;
     System.IO.BinaryReader br = new System.IO.BinaryReader(new System.IO.FileStream("Effect.shader", System.IO.FileMode.Open));
     buffer = br.ReadBytes(Convert.ToInt32(new System.IO.FileInfo("Effect.shader").Length));
     br.Close();
     ResourceCollectorXNA.Engine.Render.Materials.Material.ObjectRenderEffect = new Effect(Device, buffer);
 }
Esempio n. 54
0
		/// <summary>check that the query weight is serializable. </summary>
		/// <throws>  IOException if serialization check fail.  </throws>
		private static void  CheckSerialization(Query q, Searcher s)
		{
			Weight w = q.Weight(s);
			try
			{
				System.IO.MemoryStream bos = new System.IO.MemoryStream();
				System.IO.BinaryWriter oos = new System.IO.BinaryWriter(bos);
				System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				formatter.Serialize(oos.BaseStream, w);
				oos.Close();
				System.IO.BinaryReader ois = new System.IO.BinaryReader(new System.IO.MemoryStream(bos.ToArray()));
				formatter.Deserialize(ois.BaseStream);
				ois.Close();
				
				//skip rquals() test for now - most weights don't overide equals() and we won't add this just for the tests.
				//TestCase.assertEquals("writeObject(w) != w.  ("+w+")",w2,w);   
			}
			catch (System.Exception e)
			{
				System.IO.IOException e2 = new System.IO.IOException("Serialization failed for " + w, e);
				throw e2;
			}
		}
Esempio n. 55
0
		/// <summary>Loads the black-box logs from the previous simulation run</summary>
		internal static void LoadLogs()
		{
			string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");
			try
			{
				using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
					{
						byte[] Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
						const short Version = 1;
						byte[] Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						short Number = Reader.ReadInt16();
						if (Version != Number) throw new System.IO.InvalidDataException();
						Game.LogRouteName = Reader.ReadString();
						Game.LogTrainName = Reader.ReadString();
						Game.LogDateTime = DateTime.FromBinary(Reader.ReadInt64());
						Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
						Game.BlackBoxEntryCount = Reader.ReadInt32();
						Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
						for (int i = 0; i < Game.BlackBoxEntryCount; i++)
						{
							Game.BlackBoxEntries[i].Time = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Position = Reader.ReadDouble();
							Game.BlackBoxEntries[i].Speed = Reader.ReadSingle();
							Game.BlackBoxEntries[i].Acceleration = Reader.ReadSingle();
							Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
							Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerDriver = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].PowerSafety = (Game.BlackBoxPower)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeDriver = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].BrakeSafety = (Game.BlackBoxBrake)Reader.ReadInt16();
							Game.BlackBoxEntries[i].EventToken = (Game.BlackBoxEventToken)Reader.ReadInt16();
						}
						Game.ScoreLogCount = Reader.ReadInt32();
						Game.ScoreLogs = new Game.ScoreLog[Game.ScoreLogCount];
						Game.CurrentScore.Value = 0;
						for (int i = 0; i < Game.ScoreLogCount; i++)
						{
							Game.ScoreLogs[i].Time = Reader.ReadDouble();
							Game.ScoreLogs[i].Position = Reader.ReadDouble();
							Game.ScoreLogs[i].Value = Reader.ReadInt32();
							Game.ScoreLogs[i].TextToken = (Game.ScoreTextToken)Reader.ReadInt16();
							Game.CurrentScore.Value += Game.ScoreLogs[i].Value;
						}
						Game.CurrentScore.Maximum = Reader.ReadInt32();
						Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
						Data = Reader.ReadBytes(Identifier.Length);
						for (int i = 0; i < Identifier.Length; i++)
						{
							if (Identifier[i] != Data[i]) throw new System.IO.InvalidDataException();
						}
						Reader.Close();
					} Stream.Close();
				}
			}
			catch
			{
				Game.LogRouteName = "";
				Game.LogTrainName = "";
				Game.LogDateTime = DateTime.Now;
				Game.BlackBoxEntries = new Game.BlackBoxEntry[256];
				Game.BlackBoxEntryCount = 0;
				Game.ScoreLogs = new Game.ScoreLog[64];
				Game.ScoreLogCount = 0;
			}
		}
Esempio n. 56
0
        /// <summary>
        /// 根据文件的前2个字节进行判断文件类型是不是图片
        /// </summary>
        /// <param name="hpf"></param>
        /// <returns></returns>
        public bool CheckUploadByTwoByteIsImg(HttpPostedFile hpf)
        {
            System.IO.FileStream fs = new System.IO.FileStream(hpf.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

            }
            catch
            {

            }
            r.Close();
            fs.Close();
            //说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Esempio n. 57
0
        public static System.Drawing.Bitmap LoadTGA(System.IO.Stream source)
        {
            byte[] buffer = new byte[source.Length];
            source.Read(buffer, 0, buffer.Length);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);

            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            tgaHeader header = new tgaHeader();
            header.Read(br);

            if (header.ImageSpec.PixelDepth != 8 &&
                header.ImageSpec.PixelDepth != 16 &&
                header.ImageSpec.PixelDepth != 24 &&
                header.ImageSpec.PixelDepth != 32)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.AlphaBits > 8)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.Width > 4096 ||
                header.ImageSpec.Height > 4096)
                throw new ArgumentException("Image too large.");

            System.Drawing.Bitmap b = new System.Drawing.Bitmap(
                header.ImageSpec.Width, header.ImageSpec.Height);

            System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height),
                System.Drawing.Imaging.ImageLockMode.WriteOnly,
                System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
            switch (header.ImageSpec.PixelDepth)
            {
                case 8:
                    decodeStandard8(bd, header, br);
                    break;
                case 16:
                    if (header.ImageSpec.AlphaBits > 0)
                        decodeSpecial16(bd, header, br);
                    else
                        decodeStandard16(bd, header, br);
                    break;
                case 24:
                    if (header.ImageSpec.AlphaBits > 0)
                        decodeSpecial24(bd, header, br);
                    else
                        decodeStandard24(bd, header, br);
                    break;
                case 32:
                    decodeStandard32(bd, header, br);
                    break;
                default:
                    b.UnlockBits(bd);
                    b.Dispose();
                    return null;
            }
            b.UnlockBits(bd);
            br.Close();
            return b;
        }
Esempio n. 58
0
        public static unsafe byte[] LoadTGARaw(System.IO.Stream source)
        {
            byte[] buffer = new byte[source.Length];
            source.Read(buffer, 0, buffer.Length);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);

            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            tgaHeader header = new tgaHeader();
            header.Read(br);

            if (header.ImageSpec.PixelDepth != 8 &&
                header.ImageSpec.PixelDepth != 16 &&
                header.ImageSpec.PixelDepth != 24 &&
                header.ImageSpec.PixelDepth != 32)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.AlphaBits > 8)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.Width > 4096 ||
                header.ImageSpec.Height > 4096)
                throw new ArgumentException("Image too large.");

            byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4];
            System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();

            fixed (byte* pdecoded = &decoded[0])
            {
                bd.Width = header.ImageSpec.Width;
                bd.Height = header.ImageSpec.Height;
                bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
                bd.Stride = header.ImageSpec.Width * 4;
                bd.Scan0 = (IntPtr)pdecoded;

                switch (header.ImageSpec.PixelDepth)
                {
                    case 8:
                        decodeStandard8(bd, header, br);
                        break;
                    case 16:
                        if (header.ImageSpec.AlphaBits > 0)
                            decodeSpecial16(bd, header, br);
                        else
                            decodeStandard16(bd, header, br);
                        break;
                    case 24:
                        if (header.ImageSpec.AlphaBits > 0)
                            decodeSpecial24(bd, header, br);
                        else
                            decodeStandard24(bd, header, br);
                        break;
                    case 32:
                        decodeStandard32(bd, header, br);
                        break;
                    default:
                        return null;
                }
            }

            // swap red and blue channels (TGA is BGRA)
            byte tmp;
            for (int i = 0; i < decoded.Length; i += 4)
            {
                tmp = decoded[i];
                decoded[i] = decoded[i + 2];
                decoded[i + 2] = tmp;
            }

            br.Close();
            return decoded;
        }
Esempio n. 59
0
        public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mask)
        {
            byte[] buffer = new byte[source.Length];
            source.Read(buffer, 0, buffer.Length);

            System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer);

            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            tgaHeader header = new tgaHeader();
            header.Read(br);

            if (header.ImageSpec.PixelDepth != 8 &&
                header.ImageSpec.PixelDepth != 16 &&
                header.ImageSpec.PixelDepth != 24 &&
                header.ImageSpec.PixelDepth != 32)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.AlphaBits > 8)
                throw new ArgumentException("Not a supported tga file.");

            if (header.ImageSpec.Width > 4096 ||
                header.ImageSpec.Height > 4096)
                throw new ArgumentException("Image too large.");

            byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4];
            System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData();

            fixed (byte* pdecoded = &decoded[0])
            {
                bd.Width = header.ImageSpec.Width;
                bd.Height = header.ImageSpec.Height;
                bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb;
                bd.Stride = header.ImageSpec.Width * 4;
                bd.Scan0 = (IntPtr)pdecoded;

                switch (header.ImageSpec.PixelDepth)
                {
                    case 8:
                        decodeStandard8(bd, header, br);
                        break;
                    case 16:
                        if (header.ImageSpec.AlphaBits > 0)
                            decodeSpecial16(bd, header, br);
                        else
                            decodeStandard16(bd, header, br);
                        break;
                    case 24:
                        if (header.ImageSpec.AlphaBits > 0)
                            decodeSpecial24(bd, header, br);
                        else
                            decodeStandard24(bd, header, br);
                        break;
                    case 32:
                        decodeStandard32(bd, header, br);
                        break;
                    default:
                        return null;
                }
            }

            int n = header.ImageSpec.Width * header.ImageSpec.Height;
            ManagedImage image;
            
            if (mask && header.ImageSpec.AlphaBits == 0 && header.ImageSpec.PixelDepth == 8)
            {
                image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height,
                    ManagedImage.ImageChannels.Alpha);
                int p = 3;

                for (int i = 0; i < n; i++)
                {
                    image.Alpha[i] = decoded[p];
                    p += 4;
                }
            }
            else
            {
                image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height,
                    ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha);
                int p = 0;

                for (int i = 0; i < n; i++)
                {
                    image.Blue[i] = decoded[p++];
                    image.Green[i] = decoded[p++];
                    image.Red[i] = decoded[p++];
                    image.Alpha[i] = decoded[p++];
                }
            }

            br.Close();
            return image;
        }
Esempio n. 60
0
        public void readFile()
        {
            System.IO.BinaryReader sr;

            try { //TODO: test, rather than try/fail?
                sr = new System.IO.BinaryReader(System.IO.File.Open(path, System.IO.FileMode.Open));
            } catch (System.IO.IOException) {
                throw;
            }

            //====================
            //RIFF chunk id
            char[] ckID = sr.ReadChars(4);
            String a = new string(ckID);
            if (a.CompareTo("RIFF") != 0) {
                throw new FormatException("RIFF chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            UInt32 RIFFSize = sr.ReadUInt32();

            //====================
            //WAVE chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            if (a.CompareTo("WAVE") != 0) {
                throw new FormatException("WAVE chunkID missing. Found " + ckID[0] + ckID[1] + ckID[2] + ckID[3] + ".");
            }

            //====================
            //fmt_ chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            UInt32 chunkSize = sr.ReadUInt32();
            while (a.CompareTo("fmt ") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }
            Int16 wFormatTag = sr.ReadInt16();
            Int16 nChannels = sr.ReadInt16();
            Int32 nSamplesPerSec = sr.ReadInt32();
            Int32 nAvgBytesPerSec = sr.ReadInt32();
            Int16 nBlockAlign = sr.ReadInt16();
            Int16 wBitsPerSample = sr.ReadInt16();
            chunkSize -= 16;
            //there may be more bytes in fmt_ so skip those.
            sr.ReadBytes((int)chunkSize);

            if (wFormatTag != 0x0001) {
                throw new FormatException("Invalid wave format. Only PCM wave files supported.");
            }

            //====================
            //data chunk id
            ckID = sr.ReadChars(4);
            a = new string(ckID);
            chunkSize = sr.ReadUInt32();
            while (a.CompareTo("data") != 0) {
                sr.ReadBytes((int)chunkSize);
                ckID = sr.ReadChars(4);
                a = new string(ckID);
                chunkSize = sr.ReadUInt32();
            }

            channels = (short)nChannels;
            bitDepth = (short)wBitsPerSample;
            sampleRate = nSamplesPerSec;
            long numSamples = chunkSize / (bitDepth / 8) / channels;
            samples = new double[channels][];
            for (int c = 0; c < channels; c++) {
                samples[c] = new double[numSamples];
            }

            //======================
            // read samples
            if (bitDepth == 16) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming signed
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadInt16() / 32768.0;
                    }
                }
            } else if (bitDepth == 8) {
                for (int i = 0; i < numSamples; i++) {
                    for (int c = 0; c < channels; c++) {
                        //assuming unsigned
                        //normalized to -1.0..+1.0
                        samples[c][i] = (double)sr.ReadByte() / 128.0 - 1.0;
                    }
                }
            } else {
                throw new FormatException("Bit depth must be one of 8 or 16 bits.");
            }
            sr.Close();
        }