Example #1
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 void LogError(Exception ex, string source)
        {
            try
            {
                String LogFile = HttpContext.Current.Request.MapPath("/Errorlog.txt");
                if (LogFile != "")
                {
                    String Message = String.Format("{0}{0}=== {1} ==={0}{2}{0}{3}{0}{4}{0}{5}"
                             , Environment.NewLine
                             , DateTime.Now
                             , ex.Message
                             , source
                             , ex.InnerException
                             , ex.StackTrace);
                    byte[] binLogString = Encoding.Default.GetBytes(Message);

                    System.IO.FileStream loFile = new System.IO.FileStream(LogFile
                              , System.IO.FileMode.OpenOrCreate
                              , System.IO.FileAccess.Write, System.IO.FileShare.Write);
                    loFile.Seek(0, System.IO.SeekOrigin.End);
                    loFile.Write(binLogString, 0, binLogString.Length);
                    loFile.Close();
                }
            }
            catch { /*No need to catch the error here. */}
        }
Example #3
0
        public static BitmapImage LoadImage(string path)
        {
            try
            {
                var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                fs.Seek(0, System.IO.SeekOrigin.Begin);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                fs.Close();

                var ms = new System.IO.MemoryStream(bytes);
                ms.Position = 0;
                var image = new BitmapImage();
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = ms;
                image.EndInit();
                return image;
            }
            catch (Exception ex)
            {
            }
            return null;
        }
Example #4
0
 private static SQLCEVersion DetermineVersion(string filename)
 {
     var versionDictionary = new System.Collections.Generic.Dictionary<int, SQLCEVersion> 
 { 
     { 0x73616261, SQLCEVersion.SQLCE20 }, 
     { 0x002dd714, SQLCEVersion.SQLCE30},
     { 0x00357b9d, SQLCEVersion.SQLCE35},
     { 0x003d0900, SQLCEVersion.SQLCE40}
 };
     int versionLONGWORD = 0;
     try
     {
         using (var fs = new System.IO.FileStream(filename, System.IO.FileMode.Open))
         {
             fs.Seek(16, System.IO.SeekOrigin.Begin);
             using (System.IO.BinaryReader reader = new System.IO.BinaryReader(fs))
             {
                 versionLONGWORD = reader.ReadInt32();
             }
         }
     }
     catch
     {
         throw;
     }
     if (versionDictionary.ContainsKey(versionLONGWORD))
     {
         return versionDictionary[versionLONGWORD];
     }
     else
     {
         throw new ApplicationException("Unable to determine database file version");
     }
 }
Example #5
0
 /// <summary>
 /// Debug
 /// </summary>
 /// <param name="strPath">文件路径</param>
 /// <param name="msg">内容</param>
 public static void DeBug(string strPath, object msg)
 {
     System.IO.StreamWriter sw = null;
     System.IO.FileStream fs = new System.IO.FileStream(strPath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read);
     fs.Seek(0, System.IO.SeekOrigin.End);
     sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8);
     string LineText = DateTime.Now.ToString() + ", " + msg.ToString();
     sw.WriteLine(LineText);
     sw.Close();
     sw = null;
     fs.Close();
     fs = null;
 }
Example #6
0
        public System.IO.Stream CreateFileStream(string path, System.IO.FileMode mode = System.IO.FileMode.Open, System.IO.FileAccess access = System.IO.FileAccess.Read, System.IO.FileShare share = System.IO.FileShare.ReadWrite)
        {
            if (path == null) throw new ArgumentNullException(nameof(path));

            // Flags match what FileStream does internally
            NativeMethods.FileManagement.AllFileAttributeFlags flags = NativeMethods.FileManagement.AllFileAttributeFlags.SECURITY_SQOS_PRESENT | NativeMethods.FileManagement.AllFileAttributeFlags.SECURITY_ANONYMOUS;
            SafeFileHandle handle = NativeMethods.FileManagement.CreateFile(path, access, share, mode, flags);
            System.IO.Stream stream = new System.IO.FileStream(handle, access);
            if (mode == System.IO.FileMode.Append)
            {
                stream.Seek(0, System.IO.SeekOrigin.End);
            }
            return stream;
        }
Example #7
0
		protected static bool ValidateExe(string path, long time_stamp_offset, uint time_stamp)
		{
			using (var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
			using (var s = new System.IO.BinaryReader(fs))
			{
				if (fs.Length > (time_stamp_offset+4))
				{
					fs.Seek(time_stamp_offset, System.IO.SeekOrigin.Begin);
					uint ts = s.ReadUInt32();

					return ts == time_stamp;
				}
			}

			return false;
		}
Example #8
0
        public StandardFileObject(string sPath, bool fWrite)
        {
            try
            {
                m_theFile = new System.IO.FileStream(sPath,
                    (fWrite) ? System.IO.FileMode.OpenOrCreate : System.IO.FileMode.Open,
                    (fWrite) ? System.IO.FileAccess.Write : System.IO.FileAccess.Read);

                if (fWrite)
                {
                    m_theFile.Seek(0, System.IO.SeekOrigin.End);
                }

                m_fLoaded = true;
            }
            catch (System.IO.IOException)
            {
                m_theFile = null;
            }
        }
        public void extractMp3Info()
        {
            if (System.IO.File.Exists(Path))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(Path, System.IO.FileMode.Open))
                {
                    byte[] b = new byte[128];

                    fs.Seek(-128, System.IO.SeekOrigin.End);
                    fs.Read(b, 0, 128);

                    if (System.Text.Encoding.Default.GetString(b, 0, 3).CompareTo("TAG") == 0)
                    {
                        Title = System.Text.Encoding.Default.GetString(b, 3, 3).TrimEnd('\0');
                        Artists = System.Text.Encoding.Default.GetString(b, 33, 30).TrimEnd('\0');
                        Album = System.Text.Encoding.Default.GetString(b, 63, 30).TrimEnd('\0');
                    }
                    fs.Close();
                }
            }
        }
Example #10
0
        public void getMusicInfos()
        {
            if (System.IO.File.Exists(Path))
            {
                /* USING DISPOSE FROM THE OBJ ONCE THE CODE SECTION IS OVER */

                using (System.IO.FileStream fs = new System.IO.FileStream(Path, System.IO.FileMode.Open))
                {
                    byte[] b = new byte[128];

                    fs.Seek(-128, System.IO.SeekOrigin.End);
                    fs.Read(b, 0, 128);

                    if (System.Text.Encoding.Default.GetString(b, 0, 3).CompareTo("TAG") == 0)
                    {
                        Title = System.Text.Encoding.Default.GetString(b, 3, 30).TrimEnd('\0');
                        Artist = System.Text.Encoding.Default.GetString(b, 33, 30).TrimEnd('\0');
                        Album = System.Text.Encoding.Default.GetString(b, 63, 30).TrimEnd('\0');
                    }
                    fs.Close();
                }
            }
        }
        private void WriteModifications(string dataHistoryFile, IIntegrationResult result)
        {            
            System.IO.FileStream fs = new System.IO.FileStream( dataHistoryFile, System.IO.FileMode.Append);           
            fs.Seek(0, System.IO.SeekOrigin.End);

            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
            System.Xml.XmlTextWriter currentBuildInfoWriter = new System.Xml.XmlTextWriter(sw);
            currentBuildInfoWriter.Formatting = System.Xml.Formatting.Indented;

            currentBuildInfoWriter.WriteStartElement("Build");
            WriteXMLAttributeAndValue(currentBuildInfoWriter, "BuildDate", Util.DateUtil.FormatDate(result.EndTime));
            WriteXMLAttributeAndValue(currentBuildInfoWriter, "Success", result.Succeeded.ToString(CultureInfo.CurrentCulture));
            WriteXMLAttributeAndValue(currentBuildInfoWriter, "Label", result.Label);

            if (result.Modifications.Length > 0)
            {                
                currentBuildInfoWriter.WriteStartElement("modifications");

                for (int i = 0; i < result.Modifications.Length; i++)
                {
                    result.Modifications[i].ToXml(currentBuildInfoWriter);
                }
                
                currentBuildInfoWriter.WriteEndElement();                
            }

            currentBuildInfoWriter.WriteEndElement();
            sw.WriteLine();

            sw.Flush();
            fs.Flush();
            
            sw.Close();
            fs.Close();
                    
        }
        /**
         * Get a byte from file
         * @param fileIndex position of required byte in the file
         * @return the byte at position <code>fileIndex</code> in the file
         */
        public byte getByte(long fileIndex)
        {
            byte theByte = 0;

            if (isRandomAccess)
            {
                //If the file is being read via random acces,
                //then read byte from buffer, otherwise read in a new buffer.
                long theArrayIndex = fileIndex - myRAFoffset;
                if (fileIndex >= myRAFoffset && theArrayIndex < randomFileBufferSize)
                {
                    theByte = fileBytes[(int)(theArrayIndex)];
                }
                else
                {
                    try {
                        //Create a new buffer:

                        /*
                         * //When a new buffer is created, the requesting file position is
                         * //taken to be the middle of the buffer.  This is so that it will
                         * //perform equally well whether the file is being examined from
                         * //start to end or from end to start
                         * myRAFoffset = fileIndex - (myRAFbuffer/2);
                         * if(myRAFoffset<0L) {
                         *  myRAFoffset = 0L;
                         * }
                         * System.out.println("    re-read file buffer");
                         * myRandomAccessFile.seek(myRAFoffset);
                         * myRandomAccessFile.read(fileBytes);
                         * theByte = fileBytes[(int)(fileIndex-myRAFoffset)];
                         */
                        if (fileIndex < randomFileBufferSize)
                        {
                            myRAFoffset = 0L;
                        }
                        else if (fileIndex < myRAFoffset)
                        {
                            myRAFoffset = fileIndex - randomFileBufferSize + 1;
                        }
                        else
                        {
                            myRAFoffset = fileIndex;
                        }
                        //System.out.println("    re-read file buffer from "+myRAFoffset+ " for "+myRAFbuffer+" bytes");
                        //System.out.println("    seek start");
                        myRandomAccessFile.Seek(myRAFoffset, System.IO.SeekOrigin.Begin); // myRAFoffset
                        //System.out.println("        read start");
                        myRandomAccessFile.Read(fileBytes, 0, fileBytes.Length);          // fileBytes
                        //System.out.println("            read end");
                        theByte = fileBytes[(int)(fileIndex - myRAFoffset)];
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else
            {
                //If the file is not being read by random access, then the byte should be in the buffer array
                theByte = fileBytes[(int)fileIndex];
            }
            return(theByte);
        }
Example #13
0
        public int WriteFile(string Ext, int Pos, byte[] Data, int Size)
        {
            int result = 0;
            CPUContext CPUContext = StartDelaySuspend();
            try {
                string FileName;

                FileName = GetFullPathName(Ext);
                using (System.IO.FileStream File = new System.IO.FileStream(FileName, System.IO.FileMode.OpenOrCreate)) {
                    File.Seek(Pos, System.IO.SeekOrigin.Begin);
                    File.Write(Data, 0, Size);
                    result = (int)(File.Position - Pos);
                }
            }
            finally {
                EndDelaySuspend(CPUContext);
            }

            return result;
        }
Example #14
0
        /// <summary>
        /// This will return a copy of the index, but also preserve
        /// a master copy in this object that is read-only.
        /// </summary>
        /// <param name="filename">The filename of the dbf file to index</param>
        /// <returns>returns a List of long offsets.  The index in the list is the row value.</returns>
        public List<long> GetIndex(string filename)
        {
            List<long> OffsetsCopy = new List<long>();
            _offsets = new List<long>();
            if (filename == null)
            {
                throw new ArgumentNullException(filename);
            }
            // check for the file existing here, otherwise we will not get an error
            //until we read the first record or read the header.
            if (!System.IO.File.Exists(filename))
            {
                throw new System.IO.FileNotFoundException(String.Format("Could not find file \"{0}\"", filename));
            }
            _filename = filename;

            _header = new dBaseHeader();
            // read the header
            System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader binaryreader = new System.IO.BinaryReader(stream);
            _header.ReadHeader(binaryreader);

            int iCurrentRecord = 0;
            long CurrentOffset = _header.HeaderLength;
            byte DeleteChar = Convert.ToByte('*');
            int RowLength = _header.RecordLength;
            while (iCurrentRecord < _header.NumRecords)
            {
                int Val = stream.ReadByte();
                if (stream.ReadByte() != DeleteChar)
                {
                    _offsets.Add(CurrentOffset);
                    OffsetsCopy.Add(CurrentOffset);
                    iCurrentRecord++;
                }
                stream.Seek(RowLength - 1, System.IO.SeekOrigin.Current);
                CurrentOffset += RowLength;
            }
            binaryreader.Close();
            stream.Close();
            binaryreader.Close();
            return OffsetsCopy;




        }
Example #15
0
 public override long Seek(long offset, System.IO.SeekOrigin origin)
 {
     return(innerStream.Seek(offset, origin));
 }
            private void save(string tosave)
            {
                if (dateandtime)
                {
                    int day = DateTime.Now.Day, month = DateTime.Now.Month;
                    int hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second;

                    string D = day < 10 ? "0" + day : "" + day;
                    string M = month < 10 ? "0" + month : "" + day;
                    string Y = "" + DateTime.Now.Year;

                    string h = hour < 10 ? "0" + hour : "" + hour;
                    string m = minute < 10 ? "0" + minute : "" + minute;
                    string s = second < 10 ? "0" + second : "" + second;

                    tosave = "" + D + '-' + M + '-' + Y + ' ' + h + ':' + m + ':' + s + ' ' + tosave;
                }

                System.IO.FileStream stream = new System.IO.FileStream(logfile, System.IO.FileMode.OpenOrCreate);
                System.IO.StreamWriter writer = new System.IO.StreamWriter(stream);
                stream.Seek(0, System.IO.SeekOrigin.End);
                writer.WriteLine(tosave);
                writer.Dispose();
                stream.Close();
            }
        /// <summary>
        /// Reads from ScenDat -> go to a zone and load the floors and walls onto cOuter 
        /// </summary>
        /// <param name="num"></param>
        public void LoadZone(int num)
        {
            System.IO.FileStream fsScenData = new System.IO.FileStream(@"a:\agf5ScenData.dat",System.IO.FileMode.Open);
            fsScenData.Seek(2592,System.IO.SeekOrigin.Begin); // Pacification Fields
            int iFloorByte;
            int iCell=0;
            double dStartX=2500, dStartY=0; // where the West edge starts drawing on the canvas

            double i = dStartX;
            double j = dStartY;
            while(iCell<4096)
            {
                iFloorByte = (short)fsScenData.ReadByte();

                //usByte2 = System.Net.IPAddress.NetworkToHostOrder(usByte2);
                //get which floor this int represents
                //create image with source defined floor and place on screen
                Image imgCell = new Image();
                //if(usByte2<50)
                CroppedBitmap cbReturnedBitmap = GetFloor(iFloorByte);
                if (cbReturnedBitmap == null)
                {
                    imgCell.Visibility = Visibility.Collapsed;
                    i -= 41;
                    j += 28;
                    iCell++;
                    continue;
                }
                imgCell.Tag = (string)iCell.ToString() +" ; "+ i +" ; "+ j;
                imgCell.MouseDown+=iCell2_MouseDown;
                imgCell.Source = cbReturnedBitmap;
                imgCell.Width = 82;
                imgCell.Height = 56;
                MakeTransparent(ref imgCell);
                imgCell.SetValue(Canvas.LeftProperty, i);
                imgCell.SetValue(Canvas.TopProperty,  j);
                cOuter.Children.Add(imgCell);
                i -= 41;
                j += 28;
               iCell++;

                if(iCell%64==0) // if is the beginning of a new column
                {
                    int iWhichCol = iCell / 64;
                    i = dStartX + 41 * iWhichCol;
                    j = dStartY + 28 * iWhichCol;
                }
            }
            //usByte2 = brScenData.ReadUInt16();
            //usByte2 = brScenData.ReadUInt16();
            //MessageBox.Show(usByte2.ToString());
            //brScenData.Dispose();
            fsScenData.Dispose();
        }
Example #18
0
        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            if ((currentTableFileName == "") || (!System.IO.File.Exists(currentTableFileName)) || (currentTableDataSet == null))
            {
                System.Windows.Forms.MessageBox.Show("Error - No table to save");
                return;
            }
            System.Data.DataTable theTable = currentTableDataSet.Tables["tableDataTable"];
            if (theTable == null)
            {
                System.Windows.Forms.MessageBox.Show("Error - Main table is null.");
                return;
            }
            System.IO.FileStream outStream = new System.IO.FileStream(currentTableFileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None);
            outStream.Write(BitConverter.GetBytes(theTable.Columns.Count), 0, 4);
            int column = 0;

            for (column = 0; column < theTable.Columns.Count; column++)
            {
                switch (theTable.Columns[column].DataType.FullName)
                {
                case "System.Single":
                    outStream.Write(BitConverter.GetBytes((int)8), 0, 4);
                    break;

                case "System.String":
                    outStream.Write(BitConverter.GetBytes((int)7), 0, 4);
                    break;

                case "System.UInt32":
                    outStream.Write(BitConverter.GetBytes((int)6), 0, 4);
                    break;

                case "System.Int32":
                    outStream.Write(BitConverter.GetBytes((int)5), 0, 4);
                    break;

                case "System.Int16":
                    outStream.Write(BitConverter.GetBytes((int)3), 0, 4);
                    break;

                case "System.Byte":
                    outStream.Write(BitConverter.GetBytes((int)2), 0, 4);
                    break;

                case "System.SByte":
                    outStream.Write(BitConverter.GetBytes((int)1), 0, 4);
                    break;

                default:
                    outStream.Write(BitConverter.GetBytes((int)5), 0, 4);
                    break;
                }
            }
            outStream.Write(BitConverter.GetBytes((int)theTable.Rows.Count), 0, 4);
            for (int row = 0; row < theTable.Rows.Count; row++)
            {
                object[] theRowData = theTable.Rows[row].ItemArray;
                for (column = 0; column < theTable.Columns.Count; column++)
                {
                    switch (theTable.Columns[column].DataType.FullName)
                    {
                    case "System.Single":
                        outStream.Write(BitConverter.GetBytes((System.Single)theRowData[column]), 0, 4);
                        break;

                    case "System.String":
                        string theString = (string)theRowData[column];
                        if ((theString == null) || (theString.Length == 0))
                        {
                            outStream.Write(BitConverter.GetBytes((int)0), 0, 4);
                            break;
                        }
                        outStream.Write(BitConverter.GetBytes((int)theString.Length), 0, 4);
                        for (int i = 0; i < theString.Length; i++)
                        {
                            outStream.WriteByte((byte)theString[i]);
                        }
                        break;

                    case "System.UInt32":
                        outStream.Write(BitConverter.GetBytes((System.UInt32)theRowData[column]), 0, 4);
                        break;

                    case "System.Int32":
                        outStream.Write(BitConverter.GetBytes((System.Int32)theRowData[column]), 0, 4);
                        break;

                    case "System.Int16":
                        outStream.Write(BitConverter.GetBytes((System.Int16)theRowData[column]), 0, 2);
                        break;

                    case "System.Byte":
                        outStream.Write(BitConverter.GetBytes((System.Byte)theRowData[column]), 0, 1);
                        break;

                    case "System.SByte":
                        outStream.Write(BitConverter.GetBytes((System.SByte)theRowData[column]), 0, 1);
                        break;

                    default:
                        outStream.Write(BitConverter.GetBytes((System.Int32)theRowData[column]), 0, 4);
                        break;
                    }
                }
            }
            outStream.Seek(0, System.IO.SeekOrigin.Begin);
            int  inVal   = outStream.ReadByte();
            uint modWord = 0x0816;

            while (inVal != -1)
            {
                outStream.Seek(-1, System.IO.SeekOrigin.Current);
                byte inByte  = (byte)(inVal & 0xff);
                byte outByte = 0;

                uint tmpModWord = modWord;
                tmpModWord &= 0xff00;
                tmpModWord  = tmpModWord >> 8;
                outByte     = (byte)(tmpModWord ^ inByte);
                tmpModWord  = outByte;
                //tmpModWord = tmpModWord ^ tmpModWord;
                //tmpModWord = (tmpModWord & 0xff00) | outByte;
                tmpModWord += modWord;
                tmpModWord  = tmpModWord & 0xffff;                //eliminate overflow
                tmpModWord  = tmpModWord * 0x6081;
                tmpModWord  = tmpModWord & 0xffff;                //eliminate overflow
                tmpModWord += 0x1608;
                tmpModWord  = tmpModWord & 0xffff;                //eliminate overflow
                modWord     = tmpModWord;

                outStream.WriteByte(outByte);
                inVal = outStream.ReadByte();
            }

            outStream.Close();
        }
Example #19
0
        private void searchButton_Click(object sender, EventArgs e)
        {
            if (fileStream == null)
            {
                MessageBox.Show("Before searching you have to open a file");
                return;
            }

            if (searchString.Text.Length == 0)
            {
                MessageBox.Show("Please enter search string");
                return;
            }

            results.Rows.Clear();
            resultsLabel.Text = "0";
            fileStream.Seek(0, System.IO.SeekOrigin.Begin);

            byte[] searchData;
            if (decSearch.Checked)
            {
                string[] bytes = searchString.Text.Split(new Char[] { ',' });
                searchData = new byte[bytes.Length];

                int tabPos = 0;
                foreach (string singleDEC in bytes)
                {
                    try
                    {
                        if (singleDEC.Length == 0 || Convert.ToInt32(singleDEC) > 255)
                        {
                            MessageBox.Show("One or more decimal numbers are not in 0-255 bounds");
                            return;
                        }
                    }
                    catch (System.FormatException)
                    {
                        MessageBox.Show("One or more values are not a proper number");
                        return;
                    }

                    searchData[tabPos++] = Convert.ToByte(singleDEC);
                }
            }
            else if (hexSearch.Checked)
            {
                if ((searchString.Text.Length % 2) != 0)
                {
                    MessageBox.Show("The length of search string must be even (each HEX value lenght must be 2)");
                    return;
                }
                searchData = new byte[(int)Math.Ceiling((double)searchString.Text.Length / 2)];

                int tabPos = 0;
                for (int i = 0; i < searchString.Text.Length; i += 2)
                {
                    try
                    {
                        searchData[tabPos++] = Convert.ToByte(searchString.Text.Substring(i, 2), 16);
                    }
                    catch (System.FormatException)
                    {
                        MessageBox.Show("One or more values are not porper HEX numbers");
                        return;
                    }
                }
            }
            else
            {
                searchData = new byte[searchString.Text.Length];

                for (int i = 0; i < searchString.Text.Length; i += 1)
                {
                    searchData[i] = (byte)searchString.Text[i];
                }
            }

            if (searchData.Length == 1 && relativeCheck.Checked)
            {
                if (MessageBox.Show("If relative search is on, it's recomended to use minimum 2 values in search string. Otherwise program can stop for a longer time than usually.\nContinue anyway?", "Warning!: Working slow down", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.No)
                {
                    return;
                }
            }

            //foreach (byte b in searchData)
            //    results.Rows.Add(b.ToString());

            lastSearchSizeInBytes = searchData.Length;

            List <object> list = new List <object>();

            list.Add(this);
            list.Add(relativeCheck.Checked);
            list.Add(searchData);
            list.Add(fileStream);

            Worker       = new SearchThread();
            searchThread = new Thread(Worker.DoWork);
            searchThread.Start(list);

            searchButton.Visible     = false;
            stopSearchButton.Visible = true;
            return;

            //Here is a code that do the same as a thread, but freezes window
            int    resultCount  = 0;
            string resultString = "";

            //NORMAL METHOD
            if (!relativeCheck.Checked)
            {
                foreach (byte data in searchData)
                {
                    if (Convert.ToString(data, 16).Length == 1)
                    {
                        resultString += '0';
                    }
                    resultString += Convert.ToString(data, 16).ToUpper();
                }

                int actualData = 0;
                while ((actualData = fileStream.ReadByte()) != -1)
                {
                    long pos = fileStream.Position;
                    if (actualData == searchData[0])
                    {
                        bool found = true;
                        for (int i = 1; i < searchData.Length; i++)
                        {
                            if (!(fileStream.ReadByte() == searchData[i]))
                            {
                                found = false;
                                break;
                            }
                        }

                        if (found)
                        {
                            results.Rows.Add(pos - 1, resultString);
                            resultCount++;
                        }

                        fileStream.Seek(pos, System.IO.SeekOrigin.Begin);
                    }
                }
            }
            //RELATIVE METHOD
            else
            {
                for (int pos = 1; pos <= fileStream.Length - searchData.Length + 1; pos++)
                {
                    int beginingByte = fileStream.ReadByte();

                    resultString = "";
                    if (Convert.ToString(beginingByte, 16).Length == 1)
                    {
                        resultString += '0';
                    }
                    resultString += Convert.ToString(beginingByte, 16).ToUpper();

                    bool found = true;
                    for (int i = 1; i < searchData.Length; i++)
                    {
                        int comparisonByte = fileStream.ReadByte();
                        int dataDiff       = beginingByte - comparisonByte;
                        int targetDiff     = searchData[0] - searchData[i];

                        if (dataDiff != targetDiff)
                        {
                            found = false;
                            break;
                        }

                        if (Convert.ToString(comparisonByte, 16).Length == 1)
                        {
                            resultString += '0';
                        }
                        resultString += Convert.ToString(comparisonByte, 16).ToUpper();
                    }

                    if (found)
                    {
                        results.Rows.Add(pos - 1, resultString);
                        resultCount++;
                    }

                    fileStream.Seek(pos, System.IO.SeekOrigin.Begin);
                }
            }

            resultsLabel.Text = Convert.ToString(resultCount);
        }
 /// <summary>Random-access methods </summary>
 public override void  Seek(long pos)
 {
     base.Seek(pos);
     file.Seek(pos, System.IO.SeekOrigin.Begin);
 }
Example #21
0
        /// <summary> Constructs a Grib1BinaryDataSection object from a raf.
        /// A bit map is defined.
        ///
        /// </summary>
        /// <param name="raf">raf with BDS content
        /// </param>
        /// <param name="decimalscale">the exponent of the decimal scale
        /// </param>
        /// <param name="bms">bit map section of GRIB record
        ///
        /// </param>
        /// <throws>  NotSupportedException  if stream contains no valid GRIB file </throws>
        //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'"
        public Grib1BinaryDataSection(System.IO.FileStream raf, int decimalscale, Grib1BitMapSection bms)
        {
            // octets 1-3 (section length)
            length = (int)GribNumbers.uint3(raf);
            //System.out.println( "BDS length = " + length );

            // octet 4, 1st half (packing flag)
            int unusedbits = raf.ReadByte();

            // TODO Check this!!!
            if ((unusedbits & 192) != 0)
            {
                throw new NotSupportedException("BDS: (octet 4, 1st half) not grid point data and simple packing ");
            }

            // octet 4, 2nd half (number of unused bits at end of this section)
            unusedbits = unusedbits & 15;
            //System.out.println( "BDS unusedbits = " + unusedbits );

            // octets 5-6 (binary scale factor)
            int binscale = GribNumbers.int2(raf);

            // octets 7-10 (reference point = minimum value)
            float refvalue = GribNumbers.float4(raf);

            // octet 11 (number of bits per value)
            int numbits = raf.ReadByte();

            //System.out.println( "BDS numbits = " + numbits );
            if (numbits == 0)
            {
                isConstant = true;
            }
            //System.out.println( "BDS isConstant = " + isConstant );

            // *** read values *******************************************************

            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
            float ref_Renamed = (float)(System.Math.Pow(10.0, -decimalscale) * refvalue);
            //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
            float scale = (float)(System.Math.Pow(10.0, -decimalscale) * System.Math.Pow(2.0, binscale));

            if (bms != null)
            {
                bool[] bitmap = bms.Bitmap;

                values = new float[bitmap.Length];
                for (int i = 0; i < bitmap.Length; i++)
                {
                    if (bitmap[i])
                    {
                        if (!isConstant)
                        {
                            values[i] = ref_Renamed + scale * bits2UInt(numbits, raf);
                        }
                        else
                        {
                            // rdg - added this to handle a constant valued parameter
                            values[i] = ref_Renamed;
                        }
                    }
                    else
                    {
                        values[i] = Grib1BinaryDataSection.UNDEFINED;
                    }
                }
            }
            else
            {
                // bms is null
                if (!isConstant)
                {
                    //System.out.println( "BDS values.size = " +
                    //(((length - 11) * 8 - unusedbits) /  numbits));
                    values = new float[((length - 11) * 8 - unusedbits) / numbits];

                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = ref_Renamed + scale * bits2UInt(numbits, raf);
                    }
                }
                else
                {
                    // constant valued - same min and max
                    int x = 0, y = 0;
                    raf.Seek(raf.Position - 53, System.IO.SeekOrigin.Begin);                     // return to start of GDS
                    length = (int)GribNumbers.uint3(raf);
                    if (length == 42)
                    {
                        // Lambert/Mercator offset
                        SupportClass.Skip(raf, 3);
                        x = GribNumbers.int2(raf);
                        y = GribNumbers.int2(raf);
                    }
                    else
                    {
                        SupportClass.Skip(raf, 7);
                        length = (int)GribNumbers.uint3(raf);
                        if (length == 32)
                        {
                            // Polar sterographic
                            SupportClass.Skip(raf, 3);
                            x = GribNumbers.int2(raf);
                            y = GribNumbers.int2(raf);
                        }
                        else
                        {
                            x = y = 1;
                            System.Console.Out.WriteLine("BDS constant value, can't determine array size");
                        }
                    }
                    values = new float[x * y];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = ref_Renamed;
                    }
                }
            }
        }         // end Grib1BinaryDataSection
Example #22
0
        public bool Load(string path)
        {
            System.IO.FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
            }
            catch
            {
                return(false);
            }

            var br = new System.IO.BinaryReader(fs);

            var buf = new byte[1024];

            if (br.Read(buf, 0, 8) != 8)
            {
                fs.Dispose();
                br.Close();
                return(false);
            }

            var version = BitConverter.ToInt32(buf, 0);

            if (version == 2)
            {
                Scale = BitConverter.ToSingle(buf, 4);
                fs.Dispose();
                br.Close();
                return(false);
            }

            if (version == 3)
            {
                fs.Seek(-4, System.IO.SeekOrigin.End);

                if (br.Read(buf, 0, 4) == 4)
                {
                    Scale = BitConverter.ToSingle(buf, 0);
                }
                else
                {
                    fs.Dispose();
                    br.Close();
                    return(false);
                }
            }

            if (version == 5)
            {
                Scale = BitConverter.ToSingle(buf, 4);
                fs.Dispose();
                br.Close();
                return(true);
            }

            fs.Dispose();
            br.Close();

            return(true);
        }
Example #23
0
        private async void Button_StartScan_Click(object sender, RoutedEventArgs e)
        {
            DataGrid_RIP.DataContext = null;
            entries = new List <RIPEntry>();
            TextBox_Log.Clear();
            GC.Collect();

            if (string.IsNullOrWhiteSpace(TextBox_FilterString.Text))
            {
                var result = await MessageBox.Show("Requires huge memories to run without filter.\n If results are more than 1M, snip them.\n Procced?", "Caution", MessageBoxButton.OKCancel);

                if (result != MessageBoxResult.OK)
                {
                    return;
                }
            }


            if (this.RadioButton_Group1_Process.IsChecked == true)
            {
                if (TargetProcess == null)
                {
                    return;
                }

                //List<RIPEntry> entries = new List<RIPEntry>();
                Stopwatch stopwatch = new Stopwatch();
                SetUIEnabled(false);

                List <string> filters = ParseFilter();
                foreach (var f in filters)
                {
                    TextBox_Log.AppendText($"filter: {f}" + Environment.NewLine);
                }

                bool searchFromAllModules = CheckBox_AllModules.IsChecked ?? false;
                bool onlyLEA = CheckBox_OnlyLEA.IsChecked ?? false;

                List <ProcessModule> ProcessModules = new List <ProcessModule>();

                if (searchFromAllModules)
                {
                    foreach (ProcessModule m in TargetProcess.Modules)
                    {
                        ProcessModules.Add(m);
                    }
                }
                else
                {
                    if (ComboBox_SpecificModule.SelectedItem != null)
                    {
                        ProcessModules.Add((ProcessModule)ComboBox_SpecificModule.SelectedItem);
                    }
                    else
                    {
                        ProcessModules.Add(TargetProcess.MainModule);
                    }
                }


                var task = Task.Run(() =>
                {
                    foreach (var m in ProcessModules)
                    {
                        int moduleMemorySize = m.ModuleMemorySize;
                        IntPtr startAddres   = m.BaseAddress;
                        IntPtr endAddres     = new IntPtr(m.BaseAddress.ToInt64() + moduleMemorySize);

                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            TextBox_Log.AppendText($"----------------------------------------------------" + Environment.NewLine);

                            TextBox_Log.AppendText($"Module Name: {m.ModuleName}" + Environment.NewLine);
                            TextBox_Log.AppendText($"File Name: {m.FileName}" + Environment.NewLine);
                            TextBox_Log.AppendText($"Module Size: {moduleMemorySize.ToString("#,0")} Byte" + Environment.NewLine);
                            TextBox_Log.AppendText($"Start Address: {startAddres.ToInt64().ToString("X2")} ({startAddres.ToInt64()})" + Environment.NewLine);
                            TextBox_Log.AppendText($"End Address  : {endAddres.ToInt64().ToString("X2")} ({endAddres.ToInt64()})" + Environment.NewLine);
                            TextBox_Log.AppendText($"Scan started. Please wait..." + "  ");
                        }));

                        stopwatch.Start();

                        IntPtr currentAddress = startAddres;
                        int bufferSize        = 1 * 1024 * 1024;
                        byte[] buffer         = new byte[bufferSize];

                        while (currentAddress.ToInt64() < endAddres.ToInt64())
                        {
                            // size
                            IntPtr nSize = new IntPtr(bufferSize);

                            // if remaining memory size is less than splitSize, change nSize to remaining size
                            if (IntPtr.Add(currentAddress, bufferSize).ToInt64() > endAddres.ToInt64())
                            {
                                nSize = (IntPtr)(endAddres.ToInt64() - currentAddress.ToInt64());
                            }

                            IntPtr numberOfBytesRead = IntPtr.Zero;
                            if (Helper.ReadProcessMemory(TargetProcessHandle, currentAddress, buffer, nSize, ref numberOfBytesRead))
                            {
                                for (int i = 0; i < numberOfBytesRead.ToInt64() - 4; i++)
                                {
                                    var entry               = new RIPEntry();
                                    entry.Address           = new IntPtr(currentAddress.ToInt64() + i);
                                    entry.AddressValueInt64 = BitConverter.ToInt32(buffer, i);
                                    entry.TargetAddress     = new IntPtr(entry.Address.ToInt64() + entry.AddressValueInt64 + 4);


                                    if (entry.TargetAddress.ToInt64() < startAddres.ToInt64() || entry.TargetAddress.ToInt64() > endAddres.ToInt64())
                                    {
                                        continue;
                                    }

                                    var offsetString1 = (entry.Address.ToInt64() - startAddres.ToInt64()).ToString("X");
                                    if (offsetString1.Length % 2 == 1)
                                    {
                                        offsetString1 = "0" + offsetString1;
                                    }
                                    entry.AddressRelativeString = '"' + m.ModuleName + '"' + "+" + offsetString1;

                                    var offsetString2 = (entry.TargetAddress.ToInt64() - startAddres.ToInt64()).ToString("X");
                                    if (offsetString2.Length % 2 == 1)
                                    {
                                        offsetString2 = "0" + offsetString2;
                                    }
                                    entry.TargetAddressRelativeString = '"' + m.ModuleName + '"' + "+" + offsetString2;

                                    if (filters.Any() &&
                                        !filters.Any(x => x == entry.TargetAddressString) &&
                                        !filters.Any(x => x == entry.TargetAddressRelativeString))
                                    {
                                        continue;
                                    }

                                    // Signature
                                    int bufferSize2           = 64;
                                    byte[] buffer2            = new byte[bufferSize2];
                                    IntPtr nSize2             = new IntPtr(bufferSize2);
                                    IntPtr numberOfBytesRead2 = IntPtr.Zero;
                                    if (Helper.ReadProcessMemory(TargetProcessHandle, new IntPtr(entry.Address.ToInt64() - bufferSize2), buffer2, nSize2, ref numberOfBytesRead2))
                                    {
                                        if (numberOfBytesRead2.ToInt64() == bufferSize2)
                                        {
                                            if (onlyLEA && (buffer2.Length < 2 || buffer2[buffer2.Length - 2] != 0x8D))
                                            {
                                                continue;
                                            }
                                            entry.Signature = BitConverter.ToString(buffer2).Replace("-", "");
                                        }
                                    }

                                    if (entries.Count < MaxEntries)
                                    {
                                        entries.Add(entry);
                                    }
                                }
                            }
                            if ((currentAddress.ToInt64() + numberOfBytesRead.ToInt64()) == endAddres.ToInt64())
                            {
                                currentAddress = new IntPtr(currentAddress.ToInt64() + numberOfBytesRead.ToInt64());
                            }
                            else
                            {
                                currentAddress = new IntPtr(currentAddress.ToInt64() + numberOfBytesRead.ToInt64() - 4);
                            }
                        }

                        stopwatch.Stop();

                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            TextBox_Log.AppendText($"Complete." + Environment.NewLine);
                            TextBox_Log.AppendText($"Result Count: {entries.Count.ToString("#,0")}" + Environment.NewLine);
                            TextBox_Log.AppendText($"Scan Time: {stopwatch.ElapsedMilliseconds}ms" + Environment.NewLine);
                        }));
                    }
                });

                await task;
                DataGrid_RIP.Items = entries;
                SetUIEnabled(true);
            }
            else if (this.RadioButton_Group1_File.IsChecked == true)
            {
                if (string.IsNullOrWhiteSpace(BinFileName))
                {
                    return;
                }
                Stopwatch stopwatch = new Stopwatch();

                SetUIEnabled(false);

                List <string> filters = ParseFilter();
                foreach (var f in filters)
                {
                    TextBox_Log.AppendText($"filter: {f}" + Environment.NewLine);
                }


                var task = Task.Run(() =>
                {
                    System.IO.FileStream fs  = new System.IO.FileStream(BinFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    System.IO.FileStream fs2 = new System.IO.FileStream(BinFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                    long startPosition   = 0;
                    long endPosition     = fs.Length;
                    long currentPosition = 0;

                    int bufferSize = 8 * 1024 * 1024;
                    byte[] buffer  = new byte[bufferSize];

                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        TextBox_Log.AppendText($"----------------------------------------------------" + Environment.NewLine);
                        TextBox_Log.AppendText($"File Name: {BinFileName}" + Environment.NewLine);
                        TextBox_Log.AppendText($"Module Size: {endPosition.ToString("#,0")} Byte" + Environment.NewLine);
                        TextBox_Log.AppendText($"Scan started. Please wait..." + "  ");
                    }));

                    stopwatch.Start();

                    while (currentPosition < endPosition)
                    {
                        int readSize = fs.Read(buffer, 0, bufferSize);

                        for (int i = 0; i < readSize - 4; i++)
                        {
                            var entry               = new RIPEntry();
                            entry.Address           = new IntPtr(currentPosition + i);
                            entry.AddressValueInt64 = BitConverter.ToInt32(buffer, i);
                            entry.TargetAddress     = new IntPtr(entry.Address.ToInt64() + entry.AddressValueInt64 + 4);

                            if (entry.TargetAddress.ToInt64() < startPosition || entry.TargetAddress.ToInt64() > endPosition)
                            {
                                continue;
                            }

                            var offsetString1 = (entry.Address.ToInt64() - startPosition).ToString("X");
                            if (offsetString1.Length % 2 == 1)
                            {
                                offsetString1 = "0" + offsetString1;
                            }
                            entry.AddressRelativeString = '"' + System.IO.Path.GetFileName(BinFileName) + '"' + "+" + offsetString1;

                            var offsetString2 = (entry.TargetAddress.ToInt64() - startPosition).ToString("X");
                            if (offsetString2.Length % 2 == 1)
                            {
                                offsetString2 = "0" + offsetString2;
                            }
                            entry.TargetAddressRelativeString = '"' + System.IO.Path.GetFileName(BinFileName) + '"' + "+" + offsetString2;

                            if (filters.Any() &&
                                !filters.Any(x => x == entry.TargetAddressString) &&
                                !filters.Any(x => x == entry.TargetAddressRelativeString))
                            {
                                continue;
                            }

                            // Signature

                            int bufferSize2 = 64;
                            byte[] buffer2  = new byte[bufferSize2];
                            int offset2     = entry.Address.ToInt32() - bufferSize2;
                            if (offset2 >= 0 && offset2 + bufferSize2 <= endPosition)
                            {
                                fs2.Seek(offset2, System.IO.SeekOrigin.Begin);
                                var readBytes = fs2.Read(buffer2, 0, bufferSize2);
                                if (readBytes == bufferSize2)
                                {
                                    entry.Signature = BitConverter.ToString(buffer2).Replace("-", "");
                                }
                            }

                            if (entries.Count < MaxEntries)
                            {
                                entries.Add(entry);
                            }
                        }

                        if (readSize < bufferSize)
                        {
                            currentPosition += readSize;
                        }
                        else
                        {
                            currentPosition += (readSize - 4);
                            fs.Seek(-4, System.IO.SeekOrigin.Current);
                        }
                    }

                    fs.Close();
                    fs2.Close();

                    stopwatch.Stop();

                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        TextBox_Log.AppendText($"Complete." + Environment.NewLine);
                        TextBox_Log.AppendText($"Result Count: {entries.Count.ToString("#,0")}" + Environment.NewLine);
                        TextBox_Log.AppendText($"Scan Time: {stopwatch.ElapsedMilliseconds}ms" + Environment.NewLine);
                    }));
                });

                await task;
                DataGrid_RIP.DataContext = entries;

                SetUIEnabled(true);
            }

            GC.Collect();
        }
Example #24
0
        private void CMDGetOobClick(object sender, EventArgs e)
        {
            System.IO.FileStream fs0 = null;
            System.IO.TextReader blockfile = null;
            System.IO.TextWriter outfile = null;

            try
            {
                fs0 = new System.IO.FileStream(@"D:\PS3\dump_orig\nand1.bin", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                blockfile = new System.IO.StreamReader(@"D:\PS3\dump_orig\nand1_blocks.txt");
                outfile = new System.IO.StreamWriter(@"D:\PS3\dump_orig\nand1_oob.txt");

                var oob = new byte[6];

                var s0 = blockfile.ReadLine();
                do
                {
                    fs0.Seek(Convert.ToInt64(s0) * 0x21000 + 0x802, System.IO.SeekOrigin.Begin);
                    fs0.Read(oob, 0, oob.Length);
                    outfile.WriteLine("{0:X2} {1:X2} {2:X2} {3:X2} {4:X2} {5:X2}", oob[0], oob[1], oob[2], oob[3], oob[4], oob[5]);
                    s0 = blockfile.ReadLine();
                } while (s0 != null);

            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
            }
            finally
            {
                if (fs0 != null)
                    fs0.Close();
                if (blockfile != null)
                    blockfile.Close();
                if (outfile != null)
                    outfile.Close();
            }
        }
Example #25
0
        private void read()
        {
            try
            {
                System.IO.FileStream fs = null;
                bool canread = false;
                long fsLength = 0;
                if (!System.IO.File.Exists(filename))
                {
                    SetText("文件不存在。");
                    SetText("\n");
                    return;
                }

                int trycount = 0;
                while (!canread)
                {
                    try
                    {
                        fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                        fsLength = fs.Length;
                        canread = true;
                    }
                    catch (Exception ex)
                    {
                        if (!System.IO.File.Exists(filename))
                        {
                            SetText("文件不存在。");
                            SetText("\n");
                            return;
                        }
                        if (trycount++ > 100)
                        {
                            SetText("打开文件失败:");
                            SetText(ex.Message);
                            SetText("\n");
                            return;
                        }
                        System.Threading.Thread.Sleep(1);
                    }
                }
                try
                {
                    if (null != fs)
                    {
                        if (fsLength <= oldlenght) oldlenght = fsLength;
                        if (fsLength - oldlenght > 10485760) oldlenght = fsLength - 10485760;//最大读取10M数据
                        if (oldlenght < 0) oldlenght = 0;
                        fs.Seek(oldlenght, System.IO.SeekOrigin.Begin);
                        byte[] readdata = new byte[fsLength - oldlenght];
                        fs.Read(readdata, 0, readdata.Length);
                        string newstr = enc.GetString(readdata);
                        SetText(newstr);
                        oldlenght = fsLength;
                    }
                    fs.Close();
                }
                catch (Exception ex)
                {
                    SetText("日志查看器本身错误:" + ex.Message);
                    SetText("\n");
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                SetText("日志查看器本身错误:" + ex.Message);
                SetText("\n");
            }
        }
 /**
  * Reads in the binary file specified.
  *
  * <p>If there are any problems reading in the file, it gets classified as unidentified,
  * with an explanatory warning message.
  */
 private void readFile() {
     
     //If file is not readable or is empty, then it gets classified
     //as unidentified (with an explanatory warning)
     
     if( !file.Exists )
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File does not exist");
         return;
     }
     
     //TODO: figure out how to port this
     /*
     if( !file.canRead() )
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File cannot be read");
         return;
     }
     */
     
     if (System.IO.Directory.Exists(file.FullName))
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("This is a directory, not a file");
         return;
     }
     
     //FileInputStream binStream;
     System.IO.FileStream binStream;
     
     try
     {
         binStream = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //FileInputStream(file);
     }
     catch (System.IO.FileNotFoundException)
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File disappeared or cannot be read");
         return;
     }
     
     try {
         
         int numBytes = 100; //binStream.available();
         
         if (numBytes > 0)
         {
             //BufferedInputStream buffStream = new BufferedInputStream(binStream);
             System.IO.BufferedStream buffStream = new System.IO.BufferedStream(binStream);
             
             fileBytes = new byte[numBytes];
             int len = buffStream.Read(fileBytes, 0, numBytes);
             
             if(len != numBytes) {
                 //This means that all bytes were not successfully read
                 this.SetErrorIdentification();
                 this.SetIdentificationWarning("Error reading file: "+ len.ToString() + " bytes read from file when " + numBytes.ToString() + " were expected");
             }
             else if(len != -1)
             {
                 //This means that the end of the file was not reached
                 this.SetErrorIdentification();
                 this.SetIdentificationWarning("Error reading file: Unable to read to the end");
             }
             else
             {
                 myNumBytes = (long) numBytes;
             }
             
             buffStream.Close();
         } else {
             //If file is empty , status is error
             this.SetErrorIdentification();
             myNumBytes = 0L;
             this.SetIdentificationWarning("Zero-length file");
             
         }
         binStream.Close();
         
         isRandomAccess = false;
     } catch(System.IO.IOException e) {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("Error reading file: " + e.ToString());
     }
     catch(System.OutOfMemoryException)
     {
         try {
             myRandomAccessFile = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //RandomAccessFile(file,"r");
             isRandomAccess = true;
             
             //record the file size
             myNumBytes = myRandomAccessFile.Length;
             //try reading in a buffer
             myRandomAccessFile.Seek(0, System.IO.SeekOrigin.Begin); //(0L);
             bool tryAgain = true;
             while(tryAgain) {
                 try
                 {
                     fileBytes = new byte[(int)randomFileBufferSize];
                     myRandomAccessFile.Read(fileBytes, 0, randomFileBufferSize);
                     // .read(fileBytes);
                     tryAgain = false;
                 }
                 catch(OutOfMemoryException e4)
                 {
                     randomFileBufferSize = randomFileBufferSize/RAF_BUFFER_REDUCTION_FACTOR;
                     if(randomFileBufferSize< MIN_RAF_BUFFER_SIZE) {
                         throw e4;
                     }
                     
                 }
             }
             
             myRAFoffset = 0L;
         }
         catch (System.IO.FileNotFoundException)
         {
             this.SetErrorIdentification();
             this.SetIdentificationWarning("File disappeared or cannot be read");
         }
         catch(Exception e2)
         {
             try
             {
                 myRandomAccessFile.Close();
             }
             catch(System.IO.IOException)
             {
             }
             
             this.SetErrorIdentification();
             this.SetIdentificationWarning("Error reading file: " + e2.ToString());
         }
         
     }
 }    
Example #27
0
 public override void  Seek(long pos)
 {
     buffer.Seek(pos, System.IO.SeekOrigin.Begin);
 }
Example #28
0
			public override void  ReadBytes(byte[] b, int offset, int len)
			{
				while (len > curAvail)
				{
					// curBuf.get_Renamed(b, offset, curAvail);    // {{Aroush-1.9}}
					len -= curAvail;
					offset += curAvail;
					curBufIndex++;
					curBuf = buffers[curBufIndex]; // index out of bounds when too many bytes requested
					curBuf.Seek(0, System.IO.SeekOrigin.Begin);
					curAvail = bufSizes[curBufIndex];
				}
				// curBuf.get_Renamed(b, offset, len); // {{Aroush-1.9}}
				curAvail -= len;
			}
Example #29
0
        public static SqlBytes GetFileBlock(SqlString strFileName, SqlInt64 lOffsetBytes, SqlInt32 iLengthBytes,
            SqlString strFileShare)
        {
            System.IO.FileShare fileShare;
            if (!Enum.TryParse<System.IO.FileShare>(strFileShare.Value, out fileShare))
            {
                StringBuilder sb = new StringBuilder("Invalid System.IO.FileShare value. Received " +
                    strFileShare.Value + ". Valid values are: ");

                System.IO.FileShare[] fss = (System.IO.FileShare[])Enum.GetValues(typeof(System.IO.FileShare));

                for (int i = 0; i < fss.Length; i++)
                {
                    sb.Append(fss[i].ToString());
                    if ((i + 1) < fss.Length)
                        sb.Append(", ");
                }

                sb.Append(".");

                throw new ArgumentException(sb.ToString());
            }

            byte[] bBuffer = new byte[iLengthBytes.Value];

            using (System.IO.FileStream fs = new System.IO.FileStream(
                strFileName.Value, System.IO.FileMode.Open,
                System.IO.FileAccess.Read, fileShare,
                1024 * 64, System.IO.FileOptions.RandomAccess))
            {
                fs.Seek(lOffsetBytes.Value, System.IO.SeekOrigin.Begin);
                fs.Read(bBuffer, 0, iLengthBytes.Value);
            }

            return new SqlBytes(bBuffer);
        }
Example #30
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;
                    }
                }
            }
        }
Example #31
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("补丁准备.exe PSP_GAME的父目录 输出文件");
                return;
            }

            string dir = args[0];
            string bin = args[1];

            if (dir[dir.Length - 1] != '\\')
            {
                dir += '\\';
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream(补丁准备.Properties.Resources.data0);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);

            int num = br.ReadInt32();

            int[]  off_S   = new int[files.Length];
            int[]  size_S  = new int[files.Length];
            uint[] crc32_S = new uint[files.Length];

            for (int i = 0; i < files.Length; i++)
            {
                string name = br.ReadString();
                if (name != files[i])
                {
                    throw new Exception("程序损坏!");
                }

                off_S[i]   = br.ReadInt32();
                size_S[i]  = br.ReadInt32();
                crc32_S[i] = br.ReadUInt32();
            }

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


            System.IO.FileStream   fs = System.IO.File.Create(bin);
            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);

            bw.Write(files.Length);
            fs.Seek(4, System.IO.SeekOrigin.Current);

            int off_A = 0;

            int  off_boot   = 0;
            int  size_boot  = 0;
            uint crc32_boot = 0;

            ms = new System.IO.MemoryStream();

            for (int i = 0; i < files.Length; i++)
            {
                string file_name = files[i];
                bw.Write(file_name);

                if (file_name == BOOT || file_name == EBOOT)
                {
                    file_name = EBOOT;
                    if (off_boot != 0)
                    {
                        bw.Write((byte)1);
                        bw.Write(off_boot);
                        bw.Write(size_boot);
                        bw.Write(crc32_boot);
                        continue;
                    }
                }

                string file_d = dir + file_name.Replace('/', '\\');

                if (System.IO.File.Exists(file_d) || file_name == EBOOT)
                {
                    int off = off_A;
                    System.IO.FileStream fs_t = System.IO.File.OpenRead(file_d);
                    int size = (int)fs_t.Length;

                    byte[] t = new byte[size];
                    fs_t.Read(t, 0, t.Length);
                    fs_t.Close();

                    uint crc32 = Crc32.GetCrc32FromByteArray(t);

                    if (file_name.IndexOf(pa) == 0 && file_name.Substring(file_name.LastIndexOf('.') + 1).ToUpper() == "PAK")
                    {
                        bw.Write((byte)2);
                        bw.Write(crc32);
                    }
                    else
                    {
                        bw.Write((byte)1);
                        bw.Write(off);
                        bw.Write(size);
                        bw.Write(crc32);

                        ms.Write(t, 0, t.Length);
                        off_A = off + size;
                    }

                    if (file_name == EBOOT)
                    {
                        off_boot   = off;
                        size_boot  = size;
                        crc32_boot = crc32;
                    }
                }
                else
                {
                    bw.Write((byte)0);
                    bw.Write(crc32_S[i]);
                }
            }

            int off_base = (int)fs.Position;

            ms.Seek(0, 0);
            CopyStream(ms, fs);

            fs.Seek(4, 0);
            bw.Write(off_base);

            bw.Close();
            fs.Close();
            ms.Close();
        }
Example #32
0
            static byte[] ReadDfsFileContent(FastXml fx, int filestart, int fileend, string dfsfile)
            {
                long size;
                {
                    int sizestart, sizeend;
                    if (!fx.FindTag("Size", filestart, fileend, out sizestart, out sizeend))
                    {
                        throw new Exception("LoadDfsFileContents: Expected <Size> for DFS file '" + dfsfile + "'");
                    }
                    string ssize = fx.GetInnerText(sizestart, sizeend);
                    if (!long.TryParse(ssize, out size) || size < 0)
                    {
                        throw new FormatException("LoadDfsFileContents: <Size> for DFS file '" + dfsfile + "' has invalid value: " + ssize);
                    }
                    if (size > 1342177280)
                    {
                        throw new Exception("LoadDfsFileContents: file size (" + size + ") for DFS file '" + dfsfile + "' too large to load into memory");
                    }
                }
                byte[] content = new byte[size];
                int contentpos = 0;
                {
                    int cstart = filestart;
                    int cend = fileend;
                    for (; ; )
                    {
                        int nodestart, nodeend;
                        if (!fx.FindTag("FileNode", cstart, cend, out nodestart, out nodeend))
                        {
                            break;
                        }
                        string chunkname = fx.GetTagInnerText("Name", nodestart, nodeend);
                        string[] chunkhosts = fx.GetTagInnerText("Host", nodestart, nodeend).Split(';');
                        int chunkpos = 0; // Excluding header.
                        for (int ichunkhost = 0; ; )
                        {
                            try
                            {
                                string chunkpath = ToNetworkPath(DfsDir, chunkhosts[ichunkhost]) + @"\" + chunkname;
                                using (System.IO.FileStream fs = new System.IO.FileStream(chunkpath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                                {
                                    {
                                        if (null == headerbuf)
                                        {
                                            headerbuf = new byte[32];
                                        }
                                        // Skip the dfs-chunk file-header...
                                        int headerlength = 0;
                                        {
                                            if (4 != fs.Read(headerbuf, 0, 4))
                                            {
                                                throw new System.IO.IOException("Unable to read DFS chunk header: " + chunkpath);
                                            }
                                            {
                                                headerlength = MyBytesToInt(headerbuf, 0);
                                                if (headerlength > 4)
                                                {
                                                    int remain = headerlength - 4;
                                                    if (remain > headerbuf.Length)
                                                    {
                                                        headerbuf = new byte[remain + 100];
                                                    }
                                                    MyStreamReadExact(fs, headerbuf, remain);
                                                }
                                            }
                                        }
                                    }

                                    if (0 != chunkpos)
                                    {
                                        fs.Seek(chunkpos, System.IO.SeekOrigin.Current);
                                    }

                                    for (; ; )
                                    {

                                        int read = fs.Read(content, contentpos, content.Length - contentpos);
                                        if (read < 1)
                                        {
                                            break;
                                        }
                                        chunkpos += read;
                                        contentpos += read;
                                        if (contentpos > content.Length)
                                        {
                                            throw new Exception("LoadDfsFileContent: read too much data from DFS file '" + dfsfile + "'; file size reported is inaccurate");
                                        }
                                    }

                                }
                                break;
                            }
                            catch (System.IO.IOException)
                            {
                                ichunkhost++;
                                if (ichunkhost >= chunkhosts.Length)
                                {
                                    throw;
                                }
                                continue;
                            }
                        }
                        cstart = nodeend;
                    }
                }
                if (contentpos < content.Length)
                {
#if DEBUG
                    throw new Exception("DEBUG:  LoadDfsFileContent: (contentpos{" + contentpos
                        + "} < content.Length{" + content.Length + "}) for DFS file '" + dfsfile + "'");
#endif
                    byte[] newcontent = new byte[contentpos];
                    Buffer.BlockCopy(content, 0, newcontent, 0, contentpos);
                    content = newcontent;
                }
                return content;
            }
Example #33
0
        /// <summary>  
        /// 写入文本  
        /// </summary>  
        /// <param name="content">文本内容</param>  
        private void Write(string content, string newLine)
        {
            if (string.IsNullOrEmpty(_fileName))
            {
                return;
                //throw new Exception("FileName不能为空!");
            }

            using (System.IO.FileStream fs = new System.IO.FileStream(_fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, 8, System.IO.FileOptions.Asynchronous))
            {
                //Byte[] dataArray = System.Text.Encoding.ASCII.GetBytes(System.DateTime.Now.ToString() + content + "/r/n");
                byte[] dataArray = System.Text.Encoding.UTF8.GetBytes(content + newLine);
                bool flag = true;
                long slen = dataArray.Length;
                long len = 0;
                lock (_lock)
                {
                    while (flag)
                    {
                        try
                        {
                            if (len >= fs.Length)
                            {
                                fs.Lock(len, slen);
                                lockDic[len] = slen;
                                flag = false;
                            }
                            else
                            {
                                len = fs.Length;
                            }
                        }
                        catch (Exception)
                        {
                            while (!lockDic.ContainsKey(len))
                            {
                                len += lockDic[len];
                            }
                        }
                    }

                    fs.Seek(len, System.IO.SeekOrigin.Begin);
                    fs.Write(dataArray, 0, dataArray.Length);
                }
                fs.Close();
            }
        }
Example #34
0
        public static FileType GetFileType(string filename)
        {
            byte[] buffer = new byte[8] {
                0, 0, 0, 0, 0, 0, 0, 0
            };

            if (System.IO.File.Exists(filename))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                {
                    fs.Read(buffer, 0, buffer.Length);

                    if (buffer.Take(ZipHdr.Length).SequenceEqual(ZipHdr))
                    {
                        return(FileType.Zip);
                    }
                    else if (buffer.Take(CabHdr.Length).SequenceEqual(CabHdr))
                    {
                        return(FileType.Cab);
                    }
                    else if (buffer.Take(RarHdr.Length).SequenceEqual(RarHdr))
                    {
                        return(FileType.Rar);
                    }
                    else if (buffer.Take(GZipHdr.Length).SequenceEqual(GZipHdr))
                    {
                        return(FileType.GZip);
                    }
                    else if (buffer.Take(OleHdr.Length).SequenceEqual(OleHdr))
                    {
                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                        return(GetOleFileType(fs));
                    }
                    else if (buffer.Take(PstHdr.Length).SequenceEqual(PstHdr))
                    {
                        return(FileType.Pst);
                    }
                    else if (buffer.Take(PdfHdr.Length).SequenceEqual(PdfHdr))
                    {
                        return(FileType.Pdf);
                    }
                    else if (buffer.Take(WmfHdr.Length).SequenceEqual(WmfHdr))
                    {
                        return(FileType.Wmf);
                    }
                    else if (buffer.Take(PngHdr.Length).SequenceEqual(PngHdr))
                    {
                        return(FileType.Png);
                    }
                    else if (buffer.Take(Tiff1Hdr.Length).SequenceEqual(Tiff1Hdr))
                    {
                        return(FileType.Tiff);
                    }
                    else if (buffer.Take(Tiff2Hdr.Length).SequenceEqual(Tiff2Hdr))
                    {
                        return(FileType.Tiff);
                    }
                    else if (buffer.Take(Tiff3Hdr.Length).SequenceEqual(Tiff3Hdr))
                    {
                        return(FileType.Tiff);
                    }
                    else if (buffer.Take(Tiff4Hdr.Length).SequenceEqual(Tiff4Hdr))
                    {
                        return(FileType.Tiff);
                    }
                    else if (buffer.Take(ExeDll.Length).SequenceEqual(ExeDll))
                    {
                        return(FileType.ExeDll);
                    }
                    else if (buffer.Take(Jpeg.Length).SequenceEqual(Jpeg))
                    {
                        return(FileType.Jpeg);
                    }
                    else if (buffer.Take(Gif.Length).SequenceEqual(Gif))
                    {
                        return(FileType.Gif);
                    }
                }
            }

            return(FileType.Unknown);
        }
Example #35
0
			public override byte ReadByte()
			{
				// Performance might be improved by reading ahead into an array of
				// eg. 128 bytes and readByte() from there.
				if (curAvail == 0)
				{
					curBufIndex++;
					curBuf = buffers[curBufIndex]; // index out of bounds when too many bytes requested
					curBuf.Seek(0, System.IO.SeekOrigin.Begin);
					curAvail = bufSizes[curBufIndex];
				}
				curAvail--;
				return 0;   // return curBuf.get_Renamed();     // {{Aroush-1.9}}
			}
Example #36
0
        public bool SendImage(string Path)
        {
            bool Result = true;

            LogFile.Log("Sending programmer: " + Path, LogType.FileOnly);

            int    Step   = 0;
            UInt32 Offset = 0;
            UInt32 Length = 0;

            byte[] ImageBuffer = null;
            try
            {
                Step = 1;
                byte[] Hello = null;
                Hello = Serial.GetResponse(new byte[] { 0x01, 0x00, 0x00, 0x00 });

                // Incoming Hello packet:
                // 00000001 = Hello command id
                // xxxxxxxx = Length
                // xxxxxxxx = Protocol version
                // xxxxxxxx = Supported version
                // xxxxxxxx = Max packet length
                // xxxxxxxx = Expected mode
                // 6 dwords reserved space
                LogFile.Log("Protocol: 0x" + ByteOperations.ReadUInt32(Hello, 0x08).ToString("X8"), LogType.FileOnly);
                LogFile.Log("Supported: 0x" + ByteOperations.ReadUInt32(Hello, 0x0C).ToString("X8"), LogType.FileOnly);
                LogFile.Log("MaxLength: 0x" + ByteOperations.ReadUInt32(Hello, 0x10).ToString("X8"), LogType.FileOnly);
                LogFile.Log("Mode: 0x" + ByteOperations.ReadUInt32(Hello, 0x14).ToString("X8"), LogType.FileOnly);

                // Packet:
                // 00000002 = Hello response command id
                // 00000030 = Length
                // 00000002 = Protocol version
                // 00000001 = Supported version
                // 00000000 = Status OK
                // 00000000 = Mode
                // rest is reserved space
                Step = 2;
                byte[] HelloResponse = new byte[] {
                    0x02, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                };
                Serial.SendData(HelloResponse);

                Step = 3;
                using (System.IO.FileStream FileStream = new System.IO.FileStream(Path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    while (true)
                    {
                        Step = 4;
                        byte[] ReadDataRequest = Serial.GetResponse(null);
                        UInt32 ResponseID      = ByteOperations.ReadUInt32(ReadDataRequest, 0);
                        if (ResponseID == 4)
                        {
                            break;
                        }
                        if (ResponseID != 3)
                        {
                            Step = 5;
                            throw new BadConnectionException();
                        }

                        Offset = ByteOperations.ReadUInt32(ReadDataRequest, 0x0C);
                        Length = ByteOperations.ReadUInt32(ReadDataRequest, 0x10);
                        if ((ImageBuffer == null) || (ImageBuffer.Length != Length))
                        {
                            ImageBuffer = new byte[Length];
                        }
                        if (FileStream.Position != Offset)
                        {
                            FileStream.Seek(Offset, System.IO.SeekOrigin.Begin);
                        }

                        Step = 6;
                        FileStream.Read(ImageBuffer, 0, (int)Length);

                        Step = 7;
                        Serial.SendData(ImageBuffer);
                    }
                }
            }
            catch (Exception Ex)
            {
                LogFile.LogException(Ex, LogType.FileAndConsole, Step.ToString() + " 0x" + Offset.ToString("X8") + " 0x" + Length.ToString("X8"));
                Result = false;
            }

            if (Result)
            {
                LogFile.Log("Programmer loaded into phone memory", LogType.FileOnly);
            }

            return(Result);
        }
Example #37
0
			public override void  Seek(long pos)
			{
				curBufIndex = (int) (pos / maxBufSize);
				curBuf = buffers[curBufIndex];
				int bufOffset = (int) (pos - (curBufIndex * maxBufSize));
				curBuf.Seek(bufOffset, System.IO.SeekOrigin.Begin);
				curAvail = bufSizes[curBufIndex] - bufOffset;
			}
Example #38
0
        public static FileType GetFileType(string filename)
        {
            byte[] buffer = new byte[8]{0, 0, 0, 0, 0, 0, 0, 0};

            if (System.IO.File.Exists(filename))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                {
                    fs.Read(buffer, 0, buffer.Length);

                    if (buffer.Take(ZipHdr.Length).SequenceEqual(ZipHdr))
                        return FileType.Zip;
                    else if (buffer.Take(CabHdr.Length).SequenceEqual(CabHdr))
                        return FileType.Cab;
                    else if (buffer.Take(RarHdr.Length).SequenceEqual(RarHdr))
                        return FileType.Rar;
                    else if (buffer.Take(GZipHdr.Length).SequenceEqual(GZipHdr))
                        return FileType.GZip;
                    else if (buffer.Take(OleHdr.Length).SequenceEqual(OleHdr))
                    {
                        fs.Seek(0, System.IO.SeekOrigin.Begin);
                        return GetOleFileType(fs);
                    }
                    else if (buffer.Take(PstHdr.Length).SequenceEqual(PstHdr))
                        return FileType.Pst;
                    else if (buffer.Take(PdfHdr.Length).SequenceEqual(PdfHdr))
                        return FileType.Pdf;
                    else if (buffer.Take(WmfHdr.Length).SequenceEqual(WmfHdr))
                        return FileType.Wmf;
                    else if (buffer.Take(PngHdr.Length).SequenceEqual(PngHdr))
                        return FileType.Png;
                    else if (buffer.Take(Tiff1Hdr.Length).SequenceEqual(Tiff1Hdr))
                        return FileType.Tiff;
                    else if (buffer.Take(Tiff2Hdr.Length).SequenceEqual(Tiff2Hdr))
                        return FileType.Tiff;
                    else if (buffer.Take(Tiff3Hdr.Length).SequenceEqual(Tiff3Hdr))
                        return FileType.Tiff;
                    else if (buffer.Take(Tiff4Hdr.Length).SequenceEqual(Tiff4Hdr))
                        return FileType.Tiff;
                    else if (buffer.Take(ExeDll.Length).SequenceEqual(ExeDll))
                        return FileType.ExeDll;
                    else if (buffer.Take(Jpeg.Length).SequenceEqual(Jpeg))
                        return FileType.Jpeg;
                    else if (buffer.Take(Gif.Length).SequenceEqual(Gif))
                        return FileType.Gif;
                }
            }

            return FileType.Unknown;
        }
Example #39
0
        public static DecodeStatus DecodeArticle(Article article)
        {
            System.IO.FileStream   output = null;
            System.IO.StreamReader input  = null;

            string line;
            string decoder  = "";
            string sdecoder = "";

            string outputfile = "";
            long   outputsize = -1;

            bool  crcfailed = false;
            crc32 crc       = new crc32();

            int decodedsegments = 0;

            foreach (Segment segment in article.Segments)
            {
                // Check if the file exists, if not, skip the segment
                if (!System.IO.File.Exists(System.IO.Path.GetFullPath("Cache\\" + segment.ArticleID)))
                {
                    continue;
                }

                input = new System.IO.StreamReader(System.IO.Path.GetFullPath("Cache\\" + segment.ArticleID), System.Text.Encoding.GetEncoding("iso-8859-1"));

                // If uudecode is used, each file is automaticly a new segment
                if (decoder == "uudecode" || (decoder == "mime" && sdecoder == "base64"))
                {
                    decodedsegments++;
                }

                line = input.ReadLine();
                while (line != null)
                {
                    if (decoder == "mime")
                    {
                        if (line.StartsWith("Content-Transfer-Encoding:"))
                        {
                            sdecoder = line.Remove(0, 27);
                        }

                        if (line.StartsWith("--=") || line.StartsWith("Content-Type:"))
                        {
                            decoder  = "";
                            sdecoder = "";

                            outputfile = "";

                            output.Close();
                            output = null;
                        }

                        // Perhaps get filename out of this, but its also in the content type
                        if (line.StartsWith("Content-Disposition:"))
                        {
                            line = "";
                        }

                        if (sdecoder == "base64")
                        {
                            if (line.Length % 4 > 0)
                            {
                                line = "";
                            }

                            if (line != "")
                            {
                                byte[] buffer;
                                buffer = Convert.FromBase64String(line);

                                output.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }

                    if (decoder == "uudecode")
                    {
                        if (line != "" && line != "end")
                        {
                            char[] buffer = line.ToCharArray();
                            if (uudecode_checkline(buffer))
                            {
                                int  p = 0;
                                int  n = 0;
                                byte ch;

                                n = uudecode_dec(buffer[p]);
                                for (++p; n > 0; p += 4, n -= 3)
                                {
                                    if (n >= 3)
                                    {
                                        // Error ?
                                        if (!(uudecode_is_dec(buffer[p]) && uudecode_is_dec(buffer[p + 1]) && uudecode_is_dec(buffer[p + 2]) && uudecode_is_dec(buffer[p + 3])))
                                        {
                                            throw new Exception("33");
                                        }

                                        ch = (byte)(uudecode_dec(buffer[p + 0]) << 2 | uudecode_dec(buffer[p + 1]) >> 4);
                                        output.WriteByte(ch);
                                        ch = (byte)(uudecode_dec(buffer[p + 1]) << 4 | uudecode_dec(buffer[p + 2]) >> 2);
                                        output.WriteByte(ch);
                                        ch = (byte)(uudecode_dec(buffer[p + 2]) << 6 | uudecode_dec(buffer[p + 3]));
                                        output.WriteByte(ch);
                                    }
                                    else
                                    {
                                        if (n >= 1)
                                        {
                                            if (!(uudecode_is_dec(buffer[p]) && uudecode_is_dec(buffer[p + 1])))
                                            {
                                                throw new Exception("34");
                                            }

                                            ch = (byte)(uudecode_dec(buffer[p + 0]) << 2 | uudecode_dec(buffer[p + 1]) >> 4);
                                            output.WriteByte(ch);
                                        }
                                        if (n >= 2)
                                        {
                                            if (!(uudecode_is_dec(buffer[p + 1]) && uudecode_is_dec(buffer[p + 2])))
                                            {
                                                throw new Exception("35");
                                            }

                                            ch = (byte)(uudecode_dec(buffer[p + 1]) << 4 | uudecode_dec(buffer[p + 2]) >> 2);
                                            output.WriteByte(ch);
                                        }
                                        if (n >= 3)
                                        {
                                            if (!(uudecode_is_dec(buffer[p + 2]) && uudecode_is_dec(buffer[p + 3])))
                                            {
                                                throw new Exception("36");
                                            }

                                            ch = (byte)(uudecode_dec(buffer[p + 2]) << 6 | uudecode_dec(buffer[p + 3]));
                                            output.WriteByte(ch);
                                        }
                                    }
                                }
                            }
                        }

                        if (line == "end")
                        {
                            decoder    = "";
                            outputfile = "";

                            output.Close();
                            output = null;
                        }
                    }

                    if (decoder == "yenc")
                    {
                        if (line.StartsWith("=ypart "))
                        {
                            // Part description
                            string[] ypart = line.Split(" ".ToCharArray());
                            foreach (string s in ypart)
                            {
                                if (s.StartsWith("begin"))
                                {
                                    output.Seek(long.Parse(s.Remove(0, 6)) - 1, System.IO.SeekOrigin.Begin);
                                }
                            }
                        }
                        else
                        {
                            if (line.StartsWith("=yend "))
                            {
                                // End of the Yenc part, do CRC check
                                decoder = "";

                                string[] yend = line.Split(" ".ToCharArray());
                                foreach (string s in yend)
                                {
                                    if (s.StartsWith("pcrc32"))
                                    {
                                        long opcrc = Convert.ToInt64(s.Remove(0, 7), 16);
                                        long cpcrc = crc.EndByteCRC();

                                        if (opcrc != cpcrc)
                                        {
                                            crcfailed = true;
                                        }
                                    }
                                }
                                decodedsegments++;

                                if (outputsize == output.Length)
                                {
                                    outputsize = -1;
                                }

                                if (outputsize == -1)
                                {
                                    output.Close();
                                    output = null;

                                    outputfile = "";
                                }
                            }
                            else
                            {
                                // Yenc Encoded part
                                bool escape = false;
                                foreach (char c in line.ToCharArray())
                                {
                                    if (c == '=' && !escape)
                                    {
                                        escape = true;
                                    }
                                    else
                                    {
                                        byte nc = (byte)c;
                                        if (escape)
                                        {
                                            nc     = (byte)(nc - 64);
                                            escape = false;
                                        }

                                        nc = (byte)(nc - 42);
                                        output.WriteByte(nc);
                                        crc.AddByteCRC(nc);
                                    }
                                }
                            }
                        }
                    }

                    if (decoder == "")
                    {
                        if (line.StartsWith("=ybegin "))
                        {
                            decoder = "yenc";
                            crc.StartByteCRC();

                            // Check if its a valid ybegin line, as per 1.2 line, size and name have to be present
                            if (line.IndexOf("line=") != -1 && line.IndexOf("size=") != -1 && line.IndexOf("name=") != -1)
                            {
                                int b, e;
                                b          = line.IndexOf("size=");
                                e          = line.IndexOf(" ", b);
                                outputsize = long.Parse(line.Substring(b + 5, e - b - 5));

                                b = line.IndexOf("name=");
                                if (outputfile != line.Substring(b + 5))
                                {
                                    outputfile = line.Substring(b + 5);
                                    if (article.Filename == "")
                                    {
                                        article.Filename = outputfile;
                                    }
                                    //why add second filename?
                                    //article.Filename = article.Filename + outputfile;

                                    string outputdir = GetDirectory(article);

                                    try
                                    {
                                        if (!System.IO.Directory.Exists(System.IO.Path.GetFullPath(outputdir)))
                                        {
                                            System.IO.Directory.CreateDirectory(System.IO.Path.GetFullPath(outputdir));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        frmMain.LogWriteError("Unable to create directory [" + outputdir + "]");
                                        throw(ex);
                                    }

                                    if (output != null)
                                    {
                                        output.Close();
                                        output = null;
                                    }

                                    output = new System.IO.FileStream(System.IO.Path.GetFullPath(outputdir) + "\\" + outputfile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None, 1024 * 1024);
                                }
                            }
                        }

                        if (line.StartsWith("begin 644 "))
                        {
                            decodedsegments++;

                            decoder = "uudecode";

                            outputfile = line.Remove(0, 10);
                            if (article.Filename == "")
                            {
                                article.Filename = outputfile;
                            }
                            //why add second file name?
                            //article.Filename = article.Filename + outputfile;

                            string outputdir = GetDirectory(article);

                            try
                            {
                                if (!System.IO.Directory.Exists(System.IO.Path.GetFullPath(outputdir)))
                                {
                                    System.IO.Directory.CreateDirectory(System.IO.Path.GetFullPath(outputdir));
                                }
                            }
                            catch (Exception ex)
                            {
                                frmMain.LogWriteError("Unable to create directory [" + outputdir + "]");
                                throw(ex);
                            }

                            if (output != null)
                            {
                                output.Close();
                                output = null;
                            }

                            output = new System.IO.FileStream(System.IO.Path.GetFullPath(outputdir) + "\\" + outputfile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None, 1024 * 1024);
                        }

                        if (line.StartsWith("Content-Type: application/octet-stream;"))
                        {
                            decodedsegments++;

                            decoder  = "mime";
                            sdecoder = "";

                            outputfile = line.Substring(line.IndexOf("name=") + 5);
                            if (outputfile[0] == '\"' && outputfile[outputfile.Length - 1] == '\"')
                            {
                                outputfile = outputfile.Substring(1, outputfile.Length - 2);
                            }

                            if (outputfile[0] == '\'' && outputfile[outputfile.Length - 1] == '\'')
                            {
                                outputfile = outputfile.Substring(1, outputfile.Length - 2);
                            }

                            if (article.Filename == "")
                            {
                                article.Filename = outputfile;
                            }
                            //why add second file name?
                            //article.Filename = article.Filename + outputfile;

                            string outputdir = GetDirectory(article);

                            try
                            {
                                if (!System.IO.Directory.Exists(System.IO.Path.GetFullPath(outputdir)))
                                {
                                    System.IO.Directory.CreateDirectory(System.IO.Path.GetFullPath(outputdir));
                                }
                            }
                            catch (Exception ex)
                            {
                                frmMain.LogWriteError("Unable to create directory [" + outputdir + "]");
                                throw(ex);
                            }

                            if (output != null)
                            {
                                output.Close();
                                output = null;
                            }

                            output = new System.IO.FileStream(System.IO.Path.GetFullPath(outputdir) + "\\" + outputfile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.None, 1024 * 1024);
                        }
                    }

                    line = input.ReadLine();
                }

                input.Close();
                input = null;

                if (output != null)
                {
                    output.Flush();
                }
            }

            if (output != null)
            {
                output.Close();
                output = null;
            }

            // Changed the behaviour of deleting segments, delete all segments
            // unless nothing got decoded
            if (decodedsegments != 0)
            {
                // Pretty sure everything went ok, deleting partial files...
                foreach (Segment segment in article.Segments)
                {
                    if (System.IO.File.Exists(System.IO.Path.GetFullPath("Cache\\" + segment.ArticleID)))
                    {
                        System.IO.File.Delete(System.IO.Path.GetFullPath("Cache\\" + segment.ArticleID));
                    }
                }
            }

            if (crcfailed)
            {
                return(DecodeStatus.FailedCRC);
            }

            if (decodedsegments == 0)
            {
                return(DecodeStatus.FailedNothingToDecode);
            }

            return(DecodeStatus.Decoded);
        }
Example #40
0
 /// <summary> Write out this ICCProfile header to a RandomAccessFile</summary>
 /// <param name="raf">sink for data
 /// </param>
 /// <exception cref="IOException">
 /// </exception>
 //UPGRADE_TODO: Class 'java.io.RandomAccessFile' was converted to 'System.IO.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioRandomAccessFile'"
 public virtual void  write(System.IO.FileStream raf)
 {
     raf.Seek(offProfileSize, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileSize);
     raf.Seek(offCMMTypeSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCMMTypeSignature);
     raf.Seek(offProfileVersion, System.IO.SeekOrigin.Begin); profileVersion.write(raf);
     raf.Seek(offProfileClass, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileClass);
     raf.Seek(offColorSpaceType, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwColorSpaceType);
     raf.Seek(offPCSType, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwPCSType);
     raf.Seek(offDateTime, System.IO.SeekOrigin.Begin); dateTime.write(raf);
     raf.Seek(offProfileSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwProfileSignature);
     raf.Seek(offPlatformSignature, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwPlatformSignature);
     raf.Seek(offCMMFlags, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCMMFlags);
     raf.Seek(offDeviceManufacturer, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceManufacturer);
     raf.Seek(offDeviceModel, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceModel);
     raf.Seek(offDeviceAttributes1, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceAttributes1);
     raf.Seek(offDeviceAttributesReserved, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwDeviceAttributesReserved);
     raf.Seek(offRenderingIntent, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwRenderingIntent);
     raf.Seek(offPCSIlluminant, System.IO.SeekOrigin.Begin); PCSIlluminant.write(raf);
     raf.Seek(offCreatorSig, System.IO.SeekOrigin.Begin); raf.WriteByte((System.Byte)dwCreatorSig);
     raf.Seek(offReserved, System.IO.SeekOrigin.Begin);
     raf.Write(reserved, 0, reserved.Length);
     //SupportClass.RandomAccessFileSupport.WriteRandomFile(reserved, raf);
 }