Example #1
0
        public void Test_COMPRESS_SPACE()
        {
            String FILENAME = "MultipleStorage3.cfs"; // 22Kb

            FileInfo srcFile = new FileInfo(FILENAME);

            File.Copy(FILENAME, "MultipleStorage_Deleted_Compress.cfs", true);

            CompoundFile cf = new CompoundFile("MultipleStorage_Deleted_Compress.cfs", UpdateMode.Update, true, true);

            ICFStorage st = cf.RootStorage.GetStorage("MyStorage");
            st = st.GetStorage("AnotherStorage");

            Assert.IsNotNull(st);
            st.Delete("Another2Stream");
            cf.Commit();
            cf.Close();

            CompoundFile.ShrinkCompoundFile("MultipleStorage_Deleted_Compress.cfs"); // -> 7Kb

            FileInfo dstFile = new FileInfo("MultipleStorage_Deleted_Compress.cfs");

            Assert.IsTrue(srcFile.Length > dstFile.Length);

        }
        public override WFState Run()
        {
            WFState retval = new WFState() { Value = "Success" };

            OpenMcdf.CompoundFile cf = null;
            try
            {
                cf = new CompoundFile(this.FileToProcess);
                bool attachfound = false;
                int attachinc = 0;
                do
                {
                    CFStorage cfstorage = this.GetStorage(cf.RootStorage, MakeAttachStorageName(attachinc));
                    if (cfstorage != null)
                    {
                        // check if attachment is embedded message - if so do not process
                        if (this.GetStorage(cfstorage, nameOfEmbeddedMessageStream) == null)
                        {
                            string filename = string.Format("attachment{0}", attachinc);

                            // first get filename
                            CFStream cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3001, 0x001F));
                            if (cfstream != null)
                                filename = System.Text.UnicodeEncoding.Unicode.GetString(cfstream.GetData());
                            // second get filename
                            cfstream = this.GetStream(cfstorage, MakeSubStorageStreamName(0x3701, 0x0102));
                            if (cfstream != null)
                            {
                                string filedir = string.Format("{0}\\{1}", this.ExportDirectory, WFUtilities.GetNextDirectoryNumber(this.ExportDirectory));
                                if (!Directory.Exists(filedir))
                                    Directory.CreateDirectory(filedir);
                                if (Directory.Exists(filedir))
                                {
                                    using (var bw = new BinaryWriter(File.OpenWrite(string.Format("{0}\\{1}", filedir, filename))))
                                    {
                                        bw.Write(cfstream.GetData());
                                        this.OutputFiles.Add(string.Format("{0}\\{1}", filedir, filename), "Success");
                                    }
                                }
                            }
                        }
                        attachfound = true;
                    }
                    else
                        attachfound = false;
                    attachinc++;
                } while(attachfound);
            }
            catch (Exception)
            {
                retval.Value = "Fail";
            }
            finally
            {
                if(cf != null)
                    cf.Close();
            }

            return retval;
        }
Example #3
0
        internal CFStream(CompoundFile sectorManager, IDirectoryEntry dirEntry)
            : base(sectorManager)
        {
            if (dirEntry == null || dirEntry.SID < 0)
                throw new CFException("Attempting to add a CFStream using an unitialized directory");

            this.DirEntry = dirEntry;
        }
Example #4
0
 internal MsgParser(string filePath)
 {
     CompoundFile compoundFile = new CompoundFile(filePath);
     _namedPropertyParser = new NamedPropertyParser(compoundFile);
     _propStreamReader = new PropertyStreamReader(compoundFile);
     _recipientReader = new RecipientReader(compoundFile);
     _attachmentReader = new AttachmentReader(compoundFile);
 }
 public void Dispose()
 {
     if (this.Thumbs != null)
     {
         this.Thumbs.Close();
     }
     this.Thumbs = null;
     this.CatalogMap = null;
 }
Example #6
0
        internal CFStream(CompoundFile sectorManager)
            : base(sectorManager)
        {
            this.DirEntry = new DirectoryEntry(StgType.StgStream);
            this.DirEntry.StgColor = StgColor.Black;

            sectorManager.InsertNewDirectoryEntry(this.DirEntry);
            
        }
Example #7
0
        public void Test_CREATE_STORAGE()
        {
            const String STORAGE_NAME = "NewStorage";
            CompoundFile cf = new CompoundFile();

            ICFStorage st = cf.RootStorage.AddStorage(STORAGE_NAME);

            Assert.IsNotNull(st);
            Assert.AreEqual(STORAGE_NAME, st.Name, false);
        }
Example #8
0
 private static void CreateFile(String fn)
 {
     CompoundFile cf = new CompoundFile();
     for (int i = 0; i < MAX_STREAM_COUNT; i++)
     {
         cf.RootStorage.AddStream("Test" + i.ToString()).SetData(Helpers.GetBuffer(300));
     }
     cf.Save(fileName);
     cf.Close();
 }
 public void Allocate_6000Bytes()
 {
     var path = Path.GetTempFileName();
     if (File.Exists(path)) File.Delete(path);
     using (var file = new CompoundFile(path))
     {
         var ix = file.Allocate(6000);
         Assert.AreEqual((uint) 1, ix);
     }
     if (File.Exists(path)) File.Delete(path);
 }
Example #10
0
        public RptDefinitionWriter(string filename)
        {
            _createdReport = true;
            _report = new ReportDocument();
            _report.Load(filename, OpenReportMethod.OpenReportByTempCopy);
            _rcd = _report.ReportClientDocument;

            _oleCompoundFile = new CompoundFile(filename);

            Trace.WriteLine("Loaded report");
        }
Example #11
0
        private void CreateNewFile()
        {
            CloseCurrentFile();

            cf = new CompoundFile();
            canUpdate = false;
            saveAsToolStripMenuItem.Enabled = true;

            updateCurrentFileToolStripMenuItem.Enabled = false;

            RefreshTree();
        }
 public void Allocate_FullChapter_Test()
 {
     var path = Path.GetTempFileName();
     if (File.Exists(path)) File.Delete(path);
     using (var file = new CompoundFile(path))
     {
         for (int i=0;i<4096;i++)
         {
             var ix = file.Allocate();
         }
     }
     if (File.Exists(path)) File.Delete(path);
 }
 public ThumbsDb(string fileName)
 {
     this.Thumbs = new CompoundFile(fileName);
     CompoundStreamEntry entry = this.Thumbs.Root["catalog"] as CompoundStreamEntry;
     if (entry == null)
     {
         throw new ArgumentException("Not valid Thumbs.db file.");
     }
     using (Stream stream = entry.OpenRead())
     {
         this.LoadCatalog(stream);
     }
 }
Example #14
0
        public void Test_READ_STREAM()
        {
            String filename = "report.xls";

            CompoundFile cf = new CompoundFile(filename);
            ICFStream foundStream = cf.RootStorage.GetStream("Workbook");

            byte[] temp = foundStream.GetData();

            Assert.IsNotNull(temp);
            Assert.IsTrue(temp.Length > 0);

            cf.Close();
        }
Example #15
0
        public void Test_CREATE_STORAGE_WITH_CREATION_DATE()
        {
            const String STORAGE_NAME = "NewStorage1";
            CompoundFile cf = new CompoundFile();

            ICFStorage st = cf.RootStorage.AddStorage(STORAGE_NAME);
            st.CreationDate = DateTime.Now;

            Assert.IsNotNull(st);
            Assert.AreEqual(STORAGE_NAME, st.Name, false);

            cf.Save("ProvaData.cfs");
            cf.Close();
        }
 public void ReadUsingUtf16()
 {
     var suoPath = "../../../SampleSolution/SampleSolution.v12.suo";
     var utf16 = Encoding.GetEncodings()
         .Single(x => x.Name == "utf-16")
         .GetEncoding();
     using (var solutionStream = File.OpenRead(suoPath))
     using (var compoundFile = new CompoundFile(solutionStream, UpdateMode.ReadOnly, true, true, false))
     {
         var configStream = compoundFile.RootStorage.GetStream("SolutionConfiguration");
         var bytes = configStream.GetData();
         Debug.WriteLine(utf16.GetString(bytes));
     }
 }
    public void SaveToFile()
    {
        var suoPath = "../../../SampleSolution/SampleSolution.v12.suo";
        using (var solutionStream = File.OpenRead(suoPath))
        using (var compoundFile = new CompoundFile(solutionStream, UpdateMode.ReadOnly, true, true, false))
        {
            var configStream = compoundFile.RootStorage.GetStream("SolutionConfiguration");
            var bytes = configStream.GetData();

            var utf16 = Encoding.GetEncodings()
                .Single(x => x.Name == "utf-16")
                .GetEncoding();
            File.WriteAllText("temp.txt", utf16.GetString(bytes), utf16);
        }
    }
Example #18
0
        static void Main(string[] args)
        {
            File.Delete(fileName);
            if (!File.Exists(fileName))
            {
                CreateFile(fileName);
            }

            CompoundFile cf = new CompoundFile(fileName);
            DateTime dt = DateTime.Now;
            ICFStream s = cf.RootStorage.GetStream("Test1");
            TimeSpan ts = DateTime.Now.Subtract(dt);
            Console.WriteLine(ts.TotalMilliseconds.ToString());
            Console.Read();
        }
 public void Constructor()
 {
     var path = Path.GetTempFileName();
     if (File.Exists(path)) File.Delete(path);
     using (var file = new CompoundFile(path))
     {
         Assert.IsNotNull(file);
         Assert.IsTrue(File.Exists(path));
         Assert.IsTrue(new System.IO.FileInfo(path).Length > 0);
     }
     using (var file2 = new CompoundFile(path))
     {
         Assert.IsNotNull(file2);
     }
     if (File.Exists(path)) File.Delete(path);
 }
        internal static CompoundEntry CreateEntry(CompoundFile owner, CompoundFileDirectoryEntry[] directory, uint did)
        {
            CompoundEntry entry = null;
            switch (directory[did]._mse)
            {
                case STGTY.STGTY_STORAGE:
                case STGTY.STGTY_ROOT:
                    entry = new CompoundStorageEntry();
                    break;

                case STGTY.STGTY_STREAM:
                    entry = new CompoundStreamEntry();
                    break;
            }
            if (entry != null)
            {
                entry.FOwner = owner;
                entry.Directory = directory;
                entry.DID = did;
            }
            return entry;
        }
Example #21
0
        public void Test_VISIT_ENTRIES_CORRUPTED_FILE_VALIDATION_ON()
        {
            CompoundFile f = null;


            try
            {
                f = new CompoundFile("CorruptedDoc_bug3547815.doc", UpdateMode.ReadOnly, false, false, false);
            }
            catch (Exception ex)
            {
                Assert.Fail("No exception has to be fired on creation due to lazy loading");
            }

            FileStream output = null;

            try
            {
                output = new FileStream("LogEntriesCorrupted_1.txt", FileMode.Create);

                using (TextWriter tw = new StreamWriter(output))
                {

                    VisitedEntryAction va = delegate(ICFItem item)
                       {
                           tw.WriteLine(item.Name);
                       };

                    f.RootStorage.VisitEntries(va, true);
                    tw.Flush();
                }
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is CFCorruptedFileException);
                Assert.IsTrue(f != null && f.IsClosed);

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



            }
        }
Example #22
0
 /// <summary>
 /// Read <paramref name="count"/> bytes associated with the stream object, starting from
 /// read.
 /// </summary>
 /// <param name="buffer">Array of bytes that will contain stream data</param>
 /// <param name="position">The zero-based byte position in the stream at which to begin reading
 /// the data from.</param>
 /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
 /// <returns>The count of bytes effectively read</returns>
 /// <remarks>Method may read a number of bytes lesser then the requested one.</remarks>
 /// <code>
 ///  CompoundFile cf = null;
 ///  byte[] b = Helpers.GetBuffer(1024 * 2, 0xAA); //2MB buffer
 ///  CFStream item = cf.RootStorage.GetStream("AStream");
 ///
 ///  cf = new CompoundFile("$AFILENAME.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.Default);
 ///  item = cf.RootStorage.GetStream("AStream");
 ///
 ///  byte[] buffer = new byte[2048];
 ///  item.Read(buffer, 0, 2048);
 ///  Assert.IsTrue(Helpers.CompareBuffer(b, buffer));
 /// </code>
 ///
 /// <exception cref="T:OpenMcdf.CFDisposedException">
 /// Raised when the owner compound file has been closed.
 /// </exception>
 public int Read(byte[] buffer, long position, int count)
 {
     CheckDisposed();
     return(CompoundFile.ReadData(this, position, buffer, 0, count));
 }
Example #23
0
 /// <summary>
 /// Resize stream padding with zero if enlarging, trimming data if reducing size.
 /// </summary>
 /// <param name="length">New length to assign to this stream</param>
 public void Resize(long length)
 {
     CompoundFile.SetStreamLength(this, length);
 }
Example #24
0
        /// <summary>
        /// Remove an entry from the current storage and compound file.
        /// </summary>
        /// <param name="entryName">The name of the entry in the current storage to delete</param>
        /// <example>
        /// <code>
        /// cf = new CompoundFile("A_FILE_YOU_CAN_CHANGE.cfs", UpdateMode.Update, true, false);
        /// cf.RootStorage.Delete("AStream"); // AStream item is assumed to exist.
        /// cf.Commit(true);
        /// cf.Close();
        /// </code>
        /// </example>
        /// <exception cref="T:OpenMcdf.CFDisposedException">Raised if trying to delete item from a closed compound file</exception>
        /// <exception cref="T:OpenMcdf.CFItemNotFound">Raised if item to delete is not found</exception>
        /// <exception cref="T:OpenMcdf.CFException">Raised if trying to delete root storage</exception>
        public void Delete(String entryName)
        {
            CheckDisposed();

            // Find entry to delete
            IDirectoryEntry tmp = DirectoryEntry.Mock(entryName, StgType.StgInvalid);

            this.Children.TryLookup(tmp, out IRBNode foundObj);

            if (foundObj == null)
            {
                throw new CFItemNotFound("Entry named [" + entryName + "] was not found");
            }

            //if (foundObj.GetType() != typeCheck)
            //    throw new CFException("Entry named [" + entryName + "] has not the correct type");

            if (((IDirectoryEntry)foundObj).StgType == StgType.StgRoot)
            {
                throw new CFException("Root storage cannot be removed");
            }

            IRBNode altDel;

            switch (((IDirectoryEntry)foundObj).StgType)
            {
            case StgType.StgStorage:

                CFStorage temp = new CFStorage(this.CompoundFile, ((IDirectoryEntry)foundObj));

                // This is a storage. we have to remove children items first
                foreach (IRBNode de in temp.Children)
                {
                    IDirectoryEntry ded = de as IDirectoryEntry;
                    temp.Delete(ded.Name);
                }


                // ...then we need to rethread the root of siblings tree...
                if (this.Children.Root != null)
                {
                    this.DirEntry.Child = (this.Children.Root as IDirectoryEntry).SID;
                }
                else
                {
                    this.DirEntry.Child = DirectoryEntry.NOSTREAM;
                }

                // ...and finally Remove storage item from children tree...
                this.Children.Delete(foundObj, out altDel);

                // ...and remove directory (storage) entry

                if (altDel != null)
                {
                    foundObj = altDel;
                }

                this.CompoundFile.InvalidateDirectoryEntry(((IDirectoryEntry)foundObj).SID);

                break;

            case StgType.StgStream:

                // Free directory associated data stream.
                CompoundFile.FreeAssociatedData((foundObj as IDirectoryEntry).SID);

                // Remove item from children tree
                this.Children.Delete(foundObj, out altDel);

                // Rethread the root of siblings tree...
                if (this.Children.Root != null)
                {
                    this.DirEntry.Child = (this.Children.Root as IDirectoryEntry).SID;
                }
                else
                {
                    this.DirEntry.Child = DirectoryEntry.NOSTREAM;
                }

                // Delete operation could possibly have cloned a directory, changing its SID.
                // Invalidate the ACTUALLY deleted directory.
                if (altDel != null)
                {
                    foundObj = altDel;
                }

                this.CompoundFile.InvalidateDirectoryEntry(((IDirectoryEntry)foundObj).SID);



                break;
            }

            //// Refresh recursively all SIDs (invariant for tree sorting)
            //VisitedEntryAction action = delegate(CFSItem target)
            //{
            //    if( ((IDirectoryEntry)target).SID>foundObj.SID )
            //    {
            //        ((IDirectoryEntry)target).SID--;
            //    }


            //    ((IDirectoryEntry)target).LeftSibling--;
            //};
        }
Example #25
0
        /// <summary>
        /// Saves the <paramref name="data"/> byte array to the <paramref name="outputFile"/>
        /// </summary>
        /// <param name="data">The stream as byte array</param>
        /// <param name="outputFile">The output filename with path</param>
        /// <returns></returns>
        /// <exception cref="OEFileIsCorrupt">Raised when the file is corrupt</exception>
        internal static string SaveByteArrayToFile(byte[] data, string outputFile)
        {
            // Because the data is stored in a stream we have no name for it so we
            // have to check the magic bytes to see with what kind of file we are dealing

            var extension = Path.GetExtension(outputFile);

            if (string.IsNullOrEmpty(extension))
            {
                var fileType = FileTypeSelector.GetFileTypeFileInfo(data);
                if (fileType != null && !string.IsNullOrEmpty(fileType.Extension))
                {
                    outputFile += "." + fileType.Extension;
                }

                if (fileType != null)
                {
                    extension = "." + fileType.Extension;
                }
            }

            // Check if the output file already exists and if so make a new one
            outputFile = FileManager.FileExistsMakeNew(outputFile);

            if (extension != null)
            {
                switch (extension.ToUpperInvariant())
                {
                case ".XLS":
                case ".XLT":
                case ".XLW":
                    using (var memoryStream = new MemoryStream(data))
                        using (var compoundFile = new CompoundFile(memoryStream))
                        {
                            Excel.SetWorkbookVisibility(compoundFile.RootStorage);
                            compoundFile.Save(outputFile);
                        }
                    break;

                case ".XLSB":
                case ".XLSM":
                case ".XLSX":
                case ".XLTM":
                case ".XLTX":
                    using (var memoryStream = new MemoryStream(data))
                    {
                        var file = Excel.SetWorkbookVisibility(memoryStream);
                        File.WriteAllBytes(outputFile, file.ToArray());
                    }
                    break;

                default:
                    File.WriteAllBytes(outputFile, data);
                    break;
                }
            }
            else
            {
                File.WriteAllBytes(outputFile, data);
            }

            return(outputFile);
        }
        /// <summary>
        /// This method saves all the PowerPoint embedded binary objects from the <paramref name="inputFile"/> to the
        /// <paramref name="outputFolder"/>
        /// </summary>
        /// <param name="inputFile">The binary PowerPoint file</param>
        /// <param name="outputFolder">The output folder</param>
        /// <returns></returns>
        /// <exception cref="OEFileIsPasswordProtected">Raised when the <paramref name="inputFile"/> is password protected</exception>
        internal List <string> Extract(string inputFile, string outputFolder)
        {
            using (var compoundFile = new CompoundFile(inputFile))
            {
                var result = new List <string>();
                var stream = compoundFile.RootStorage.TryGetStream("PowerPoint Document");
                if (stream == null)
                {
                    return(result);
                }

                Logger.WriteToLog("PowerPoint Document stream found");

                using (var memoryStream = new MemoryStream(stream.GetData()))
                    using (var binaryReader = new BinaryReader(memoryStream))
                    {
                        while (binaryReader.BaseStream.Position != memoryStream.Length)
                        {
                            var verAndInstance = binaryReader.ReadUInt16();
                            // ReSharper disable once UnusedVariable
                            var version  = verAndInstance & 0x000FU;        // First 4 bit of field verAndInstance
                            var instance = (verAndInstance & 0xFFF0U) >> 4; // Last 12 bit of field verAndInstance

                            var typeCode = binaryReader.ReadUInt16();
                            var size     = binaryReader.ReadUInt32();

                            // Embedded OLE objects start with code 4113
                            if (typeCode == 4113)
                            {
                                if (instance == 0)
                                {
                                    // Uncompressed
                                    var bytes = binaryReader.ReadBytes((int)size);

                                    // Check if the ole object is another compound storage node with a package stream
                                    if (Extraction.IsCompoundFile(bytes))
                                    {
                                        result.Add(Extraction.SaveFromStorageNode(bytes, outputFolder));
                                    }
                                    else
                                    {
                                        Extraction.SaveByteArrayToFile(bytes, outputFolder + Extraction.DefaultEmbeddedObjectName);
                                    }
                                }
                                else
                                {
                                    var decompressedSize       = binaryReader.ReadUInt32();
                                    var data                   = binaryReader.ReadBytes((int)size - 4);
                                    var compressedMemoryStream = new MemoryStream(data);

                                    // skip the first 2 bytes
                                    compressedMemoryStream.ReadByte();
                                    compressedMemoryStream.ReadByte();

                                    // Decompress the bytes
                                    var decompressedBytes = new byte[decompressedSize];
                                    var deflateStream     = new DeflateStream(compressedMemoryStream, CompressionMode.Decompress, true);
                                    deflateStream.Read(decompressedBytes, 0, decompressedBytes.Length);

                                    string extractedFileName;

                                    // Check if the ole object is another compound storage node with a package stream
                                    if (Extraction.IsCompoundFile(decompressedBytes))
                                    {
                                        extractedFileName = Extraction.SaveFromStorageNode(decompressedBytes, outputFolder);
                                    }
                                    else
                                    {
                                        extractedFileName = Extraction.SaveByteArrayToFile(decompressedBytes,
                                                                                           outputFolder + Extraction.DefaultEmbeddedObjectName);
                                    }

                                    if (!string.IsNullOrEmpty(extractedFileName))
                                    {
                                        result.Add(extractedFileName);
                                    }
                                }
                            }
                            else
                            {
                                binaryReader.BaseStream.Position += size;
                            }
                        }
                    }

                return(result);
            }
        }
Example #27
0
        public void Test_LAZY_LOAD_CHILDREN_()
        {
            CompoundFile cf = new CompoundFile();
            cf.RootStorage.AddStorage("Level_1")
                .AddStorage("Level_2")
                .AddStream("Level2Stream")
                .SetData(Helpers.GetBuffer(100));

            cf.Save("$Hel1");

            cf.Close();

            cf = new CompoundFile("$Hel1");
            IList<ICFItem> i = cf.GetAllNamedEntries("Level2Stream");
            Assert.IsNotNull(i[0]);
            Assert.IsTrue(i[0] is ICFStream);
            Assert.IsTrue((i[0] as ICFStream).GetData().Length == 100);
            cf.Save("$Hel2");
            cf.Close();

            if (File.Exists("$Hel1"))
            {
                File.Delete("$Hel1");
            }
               if (File.Exists("$Hel2"))
            {
                File.Delete("$Hel2");
            }
        }
Example #28
0
        public MSOfficeManipulator(string filename, string[] names)
        {
            targetModules = new List <string>();

            foreach (string s in names)
            {
                targetModules.Add(s);
            }

            // OLE Filename (make a copy so we don't overwrite the original)
            outFilename = getOutFilename(filename);
            oleFilename = outFilename;

            // Attempt to unzip as docm or xlsm OpenXML format
            try
            {
                unzipTempPath = CreateUniqueTempDirectory();
                ZipFile.ExtractToDirectory(filename, unzipTempPath);
                if (File.Exists(Path.Combine(unzipTempPath, "word", "vbaProject.bin")))
                {
                    oleFilename = Path.Combine(unzipTempPath, "word", "vbaProject.bin");
                }
                else if (File.Exists(Path.Combine(unzipTempPath, "xl", "vbaProject.bin")))
                {
                    oleFilename = Path.Combine(unzipTempPath, "xl", "vbaProject.bin");
                }
                is_OpenXML = true;
            }
            catch (Exception)
            {
                // Not OpenXML format, Maybe 97-2003 format, Make a copy
                if (File.Exists(outFilename))
                {
                    File.Delete(outFilename);
                }
                File.Copy(filename, outFilename);
            }

            // Open OLE compound file for editing
            try
            {
                cf = new CompoundFile(oleFilename, CFSUpdateMode.Update, 0);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: Could not open file " + filename);
                Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
                Console.WriteLine();
                Console.WriteLine(e.Message);
                return;
            }

            // Read relevant streams
            commonStorage = cf.RootStorage; // docm or xlsm
            if (cf.RootStorage.TryGetStorage("Macros") != null)
            {
                commonStorage = cf.RootStorage.GetStorage("Macros");                                                 // .doc
            }
            if (cf.RootStorage.TryGetStorage("_VBA_PROJECT_CUR") != null)
            {
                commonStorage = cf.RootStorage.GetStorage("_VBA_PROJECT_CUR");                                                           // xls
            }
            vbaProjectStream = commonStorage.GetStorage("VBA").GetStream("_VBA_PROJECT").GetData();
            projectStream    = commonStorage.GetStream("project").GetData();
            projectwmStream  = commonStorage.GetStream("projectwm").GetData();
            dirStream        = Decompress(commonStorage.GetStorage("VBA").GetStream("dir").GetData());

            // Read project streams as string
            projectStreamString   = Encoding.UTF8.GetString(projectStream);
            projectwmStreamString = Encoding.UTF8.GetString(projectwmStream);

            // Find all VBA modules in current file
            vbaModules = ParseModulesFromDirStream(dirStream);

            // Write streams to debug log (if verbosity enabled)
            //Console.WriteLine("Hex dump of original _VBA_PROJECT stream:\n" + Utils.HexDump(vbaProjectStream));
            //Console.WriteLine("Hex dump of original dir stream:\n" + Utils.HexDump(dirStream));
            //Console.WriteLine("Hex dump of original project stream:\n" + Utils.HexDump(projectStream));
        }
Example #29
0
 internal PropertyStreamReader(CompoundFile cf)
 {
     _compoundFile = cf;
 }
Example #30
0
 /// <summary>
 ///     Create a new CFStorage
 /// </summary>
 /// <param name="compFile">The Storage Owner - CompoundFile</param>
 internal CFStorage(CompoundFile compFile)
     : base(compFile)
 {
     DirEntry = new DirectoryEntry(StgType.StgStorage);
     compFile.InsertNewDirectoryEntry(DirEntry);
 }
Example #31
0
 internal AttachmentReader(CompoundFile cf)
 {
     _propStreamReader = new PropertyStreamReader(cf);
 }
Example #32
0
        private static void TestCode()
        {
            const int N_FACTOR = 1000;

            byte[] bA    = GetBuffer(20 * 1024 * N_FACTOR, 0x0A);
            byte[] bB    = GetBuffer(5 * 1024, 0x0B);
            byte[] bC    = GetBuffer(5 * 1024, 0x0C);
            byte[] bD    = GetBuffer(5 * 1024, 0x0D);
            byte[] bE    = GetBuffer(8 * 1024 * N_FACTOR + 1, 0x1A);
            byte[] bF    = GetBuffer(16 * 1024 * N_FACTOR, 0x1B);
            byte[] bG    = GetBuffer(14 * 1024 * N_FACTOR, 0x1C);
            byte[] bH    = GetBuffer(12 * 1024 * N_FACTOR, 0x1D);
            byte[] bE2   = GetBuffer(8 * 1024 * N_FACTOR, 0x2A);
            byte[] bMini = GetBuffer(1027, 0xEE);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            var cf = new CompoundFile(CFSVersion.Ver_3, CFSConfiguration.SectorRecycle);

            cf.RootStorage.AddStream("A").SetData(bA);
            cf.Save("OneStream.cfs");

            cf.Close();

            cf = new CompoundFile("OneStream.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle);

            cf.RootStorage.AddStream("B").SetData(bB);
            cf.RootStorage.AddStream("C").SetData(bC);
            cf.RootStorage.AddStream("D").SetData(bD);
            cf.RootStorage.AddStream("E").SetData(bE);
            cf.RootStorage.AddStream("F").SetData(bF);
            cf.RootStorage.AddStream("G").SetData(bG);
            cf.RootStorage.AddStream("H").SetData(bH);

            cf.Save("8_Streams.cfs");

            cf.Close();

            File.Copy("8_Streams.cfs", "6_Streams.cfs", true);

            cf = new CompoundFile("6_Streams.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors);
            cf.RootStorage.Delete("D");
            cf.RootStorage.Delete("G");
            cf.Commit();

            cf.Close();

            File.Copy("6_Streams.cfs", "6_Streams_Shrinked.cfs", true);

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStream("ZZZ").SetData(bF);
            cf.RootStorage.GetStream("E").Append(bE2);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.CLSID = new Guid("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStorage("MyStorage").AddStream("ANS").Append(bE);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStorage("AnotherStorage").AddStream("ANS").Append(bE);
            cf.RootStorage.Delete("MyStorage");
            cf.Commit();
            cf.Close();

            CompoundFile.ShrinkCompoundFile("6_Streams_Shrinked.cfs");

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStorage("MiniStorage").AddStream("miniSt").Append(bMini);
            cf.RootStorage.GetStorage("MiniStorage").AddStream("miniSt2").Append(bMini);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.GetStorage("MiniStorage").Delete("miniSt");


            cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Append(bE);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle);

            var myStream = cf.RootStorage.GetStream("C");
            var data     = myStream.GetData();

            Console.WriteLine(data[0] + " : " + data[data.Length - 1]);

            myStream = cf.RootStorage.GetStream("B");
            data     = myStream.GetData();
            Console.WriteLine(data[0] + " : " + data[data.Length - 1]);

            cf.Close();

            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);

            Console.ReadKey();
        }
Example #33
0
        public void Test_VISIT_STORAGE()
        {
            String FILENAME = "testVisiting.xls";

            // Remove...
            if (File.Exists(FILENAME))
                File.Delete(FILENAME);

            //Create...

            CompoundFile ncf = new CompoundFile();

            ICFStorage l1 = ncf.RootStorage.AddStorage("Storage Level 1");
            l1.AddStream("l1ns1");
            l1.AddStream("l1ns2");
            l1.AddStream("l1ns3");

            ICFStorage l2 = l1.AddStorage("Storage Level 2");
            l2.AddStream("l2ns1");
            l2.AddStream("l2ns2");

            ncf.Save(FILENAME);
            ncf.Close();


            // Read...

            CompoundFile cf = new CompoundFile(FILENAME);

            FileStream output = new FileStream("reportVisit.txt", FileMode.Create);
            TextWriter sw = new StreamWriter(output);

            Console.SetOut(sw);

            VisitedEntryAction va = delegate(ICFItem target)
            {
                sw.WriteLine(target.Name);
            };

            cf.RootStorage.VisitEntries(va, true);

            cf.Close();
            sw.Close();
        }
Example #34
0
 /// <summary>
 /// CompoundFile constructor.
 /// </summary>
 /// <param name="doc">The compound file that has excel file data.</param>
 public Workbook(CompoundFile doc)
 {
     Load(doc);
 }
Example #35
0
        public void Test_DELETE_STREAM()
        {
            String FILENAME = "MultipleStorage3.cfs";
            CompoundFile cf = new CompoundFile(FILENAME);

            ICFStorage found = null;
            VisitedEntryAction action = delegate(ICFItem item) { if (item.Name == "AnotherStorage") found = item as ICFStorage; };
            cf.RootStorage.VisitEntries(action, true);

            Assert.IsNotNull(found);

            found.Delete("Another2Stream");

            cf.Save("MultipleDeleteStream");
            cf.Close();
        }
Example #36
0
        private void Load(CompoundFile doc)
        {
            Stream stream;

            try
            {
                // see if workbook works
                stream = doc.OpenStream("Workbook");
            }
            catch (IOException)
            {
                // see if book works, if not then leak the exception
                stream = doc.OpenStream("Book");
            }

            SstRecord sst    = null;
            long      sstPos = 0;

            // record position dictionary
            SortedList <long, Biff> records = new SortedList <long, Biff>();

            _styles     = new StyleCollection(this);
            _formats    = new FormatCollection(this);
            _fonts      = new FontCollection(this);
            _palette    = new Palette(this);
            _hyperLinks = new HyperLinkCollection(this);

            while (stream.Length - stream.Position >= GenericBiff.MinimumSize)
            {
                // capture the current stream position
                long pos = stream.Position;

                // decode the record if possible
                Biff record = GetCorrectRecord(new GenericBiff(stream), stream, sst);

                // capture
                // shared string table
                if (record is SstRecord)
                {
                    Debug.Assert(sst == null);
                    sst    = (SstRecord)record;
                    sstPos = pos;
                }
                // formatting records
                else if (record is FormatRecord)
                {
                    FormatRecord f = (FormatRecord)record;
                    _formats.Add(f.Index, new Format(this, f));
                }
                else if (record is FontRecord)
                {
                    _fonts.Add(new Font(this, (FontRecord)record));
                }
                else if (record is PaletteRecord)
                {
                    _palette.Initialize((PaletteRecord)record);
                }
                else if (record is XfRecord)
                {
                    _styles.Add(new Style(this, (XfRecord)record));
                }
                else if (record is HyperLinkRecord)
                {
                    _hyperLinks.Add((HyperLinkRecord)record);
                }

                Debug.Assert(!records.ContainsKey(pos));
                // store the position and corresponding record
                records[pos] = record;
            }

            // generate the worksheets
            _sheets = new WorksheetCollection();
            foreach (Biff record in records.Values)
            {
                if (record is BoundSheetRecord)
                {
                    _sheets.Add(new Worksheet(this, (BoundSheetRecord)record, records));
                }
            }
        }
Example #37
0
        public void Test_EXISTS_STREAM_METHOD()
        {
            var cf = new CompoundFile();

            Assert.IsFalse(cf.RootStorage.ExistsStream("AStreamName"));
            cf.RootStorage.AddStream("AStreamName");
            Assert.IsTrue(cf.RootStorage.ExistsStream("AStreamName"));
        }
Example #38
0
 private void ReadMsgFileButton_Click(object sender, EventArgs e)
 {
     var msg     = new CompoundFile(@"d:\naamloos.msg");
     var storage = msg.RootStorage.GetStorage("__nameid_version1.0");
     //var namedProperties = new NamedProperties(storage);
 }
Example #39
0
        /// <summary>
        /// This method saves all the Word embedded binary objects from the <paramref name="inputFile"/> to the
        /// <paramref name="outputFolder"/>
        /// </summary>
        /// <param name="inputFile">The binary Word file</param>
        /// <param name="outputFolder">The output folder</param>
        /// <returns></returns>
        /// <exception cref="OEFileIsPasswordProtected">Raised when the <paramref name="inputFile"/> is password protected</exception>
        internal List <string> Extract(string inputFile, string outputFolder)
        {
            using (var compoundFile = new CompoundFile(inputFile))
            {
                var result = new List <string>();

                var objectPoolStorage = compoundFile.RootStorage.TryGetStorage("ObjectPool");
                if (objectPoolStorage == null)
                {
                    return(result);
                }

                Logger.WriteToLog("Object Pool stream found (Word)");

                void Entries(CFItem item)
                {
                    var childStorage = item as CFStorage;

                    if (childStorage == null)
                    {
                        return;
                    }

                    string extractedFileName;

                    if (childStorage.TryGetStream("\x0001Ole10Native") != null)
                    {
                        var compObj = childStorage.TryGetStream("\x0001CompObj");
                        if (compObj != null)
                        {
                            var compObjStream = new CompObjStream(compObj);
                            if (compObjStream.AnsiUserType == "OLE Package")
                            {
                                extractedFileName = Extraction.SaveFromStorageNode(childStorage, outputFolder, null);
                                if (!string.IsNullOrEmpty(extractedFileName))
                                {
                                    result.Add(extractedFileName);
                                }
                                return;
                            }
                        }

                        var objInfo = childStorage.TryGetStream("\x0003ObjInfo");
                        if (objInfo != null)
                        {
                            var objInfoStream = new ObjInfoStream(objInfo);
                            // We don't want to export linked objects and objects that are not shown as an icon...
                            // because these objects are already visible on the Word document
                            if (objInfoStream.Link || !objInfoStream.Icon)
                            {
                                return;
                            }
                        }

                        extractedFileName = Extraction.SaveFromStorageNode(childStorage, outputFolder, null);
                    }
                    else
                    {
                        // Get the objInfo stream to check if this is a linked file... if so then ignore it
                        var objInfo       = childStorage.GetStream("\x0003ObjInfo");
                        var objInfoStream = new ObjInfoStream(objInfo);

                        // We don't want to export linked objects and objects that are not shown as an icon...
                        // because these objects are already visible on the Word document
                        if (objInfoStream.Link || !objInfoStream.Icon)
                        {
                            return;
                        }
                        extractedFileName = Extraction.SaveFromStorageNode(childStorage, outputFolder);
                    }

                    if (!string.IsNullOrEmpty(extractedFileName))
                    {
                        result.Add(extractedFileName);
                    }
                }

                objectPoolStorage.VisitEntries(Entries, false);

                return(result);
            }
        }
Example #40
0
        static void Main(string[] args)
        {
            bool updating = false;

            int    index;
            string lang;
            string installDir;
            string bakfile;
            string file;
            string config = Path.GetFullPath("panyi.ini");

            Console.WriteLine(
                @",-------------------------------------------------.
| panyi 1.1                                       |
| Copyright 2018 zeffy <https://github.com/zeffy> |
| Simple Understanding Public License v1 (SUPL)   |
 `+---------------------------------------------+-'
  | OpenMcdf 2.1                                |
  | Copyright (c) 2010-2018, Federico Blaseotto |
  | Mozilla Public License 2.0 (MPL-2.0)        |
  `---------------------------------------------'
");
            if (!File.Exists(config))
            {
                Console.Write("panyi.ini is missing! Download the latest copy? [y/n] ");
                string input = Console.ReadLine().Trim().ToLowerInvariant();

                if (!string.IsNullOrEmpty(input) &&
                    new[] { "yes", "y" }.Contains(input))
                {
                    updating = true;
                }
                else
                {
                    Console.Write("\nCancelled by user! Press any key to exit... ");
                    Console.ReadKey(true);
                    return;
                }
            }
            else
            {
                updating = Array.IndexOf(args, "-update") != -1;
            }

            if (updating)
            {
                using (var wc = new WebClient()) {
                    string part = config + ".part";

                    Console.Write("Downloading latest panyi.ini... ");
                    try {
                        wc.DownloadFile(
                            "https://raw.githubusercontent.com/zeffy/panyi/master/panyi/panyi.ini",
                            part);
                        Console.WriteLine("Finished!\n");
                    } catch (WebException) {
                        Console.WriteLine("Failed!\n\n" +
                                          "You can download it manually from https://git.io/fAdWN");

                        Console.Write("\nPress any key to exit... ");
                        Console.ReadKey(true);
                        return;
                    }
                    if (File.Exists(config))
                    {
                        bakfile = config + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak");
                        File.Copy(config, bakfile);

                        Console.WriteLine("Copied old panyi.ini to \"{0}\"", bakfile);
                    }
                    File.Move(part, config);
                    Console.Write("\nDone! Press any key to exit... ");
                    Console.ReadKey(true);
                    return;
                }
            }

            if ((index = Array.IndexOf(args, "-lang")) != -1)
            {
                if (++index >= args.Length)
                {
                    return;
                }

                lang = args[index];
            }
            else
            {
                lang = "en";
            }

            if ((index = Array.IndexOf(args, "-file")) != -1)
            {
                if (++index >= args.Length)
                {
                    return;
                }

                file = args[index];
            }
            else
            {
                installDir = Registry.GetValue(
                    @"HKEY_CURRENT_USER\Software\Baidu\BaiduYunGuanjia",
                    "installDir",
                    null) as string;
                if (string.IsNullOrEmpty(installDir))
                {
                    return;
                }

                file = installDir + "\\resource.db";
            }

            using (var fs = new FileStream(file,
                                           FileMode.Open,
                                           FileAccess.ReadWrite,
                                           FileShare.Read))
                using (var cf = new CompoundFile(fs,
                                                 CFSUpdateMode.Update,
                                                 CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors)) {
                    CFStream  cfs = cf.RootStorage.GetStream("StringTable.xml");
                    XDocument xd  = XDocument.Parse(Encoding.UTF8.GetString(cfs.GetData()));
                    string    id;

                    if (Array.IndexOf(args, "-x") != -1)
                    {
                        Console.WriteLine("Extracting cn string table to panyi.ini...");
                        foreach (var element in xd.Root.Elements("String"))
                        {
                            if (!NativeMethods.WritePrivateProfileString("cn",
                                                                         (string)element.Attribute("id"),
                                                                         (string)element.Attribute("value"),
                                                                         config))
                            {
                                Console.WriteLine("Failed to write string!");
                            }
                        }
                    }
                    else
                    {
                        bakfile = file + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak");
                        File.Copy(file, bakfile);
                        Console.WriteLine("Copied old resource.db to \"{0}\"", bakfile);

                        Console.WriteLine("Translating string table to {0}...", lang);
                        var sb = new StringBuilder(0x200);
                        foreach (var element in xd.Root.Elements("String"))
                        {
                            id = (string)element.Attribute("id");
                            if (NativeMethods.GetPrivateProfileString(lang, id, "", sb, (uint)sb.MaxCapacity, config) > 0)
                            {
                                element.Attribute("value").SetValue(sb.ToString());
                            }
                        }
                        cfs.SetData(Encoding.UTF8.GetBytes(xd.ToString()));
                        cf.Commit(true);
                    }
                }
            Console.Write("\nDone! Press any key to exit... ");
            Console.ReadKey(true);
            return;
        }
Example #41
0
 /// <summary>
 /// Write <paramref name="count">count</paramref> bytes of a data buffer to a specific position into
 /// the current CFStream object starting from the specified position.
 /// </summary>
 /// <param name="data">Data buffer to copy bytes from</param>
 /// <param name="position">Position into the stream object to start writing from</param>
 /// <param name="offset">The zero-based byte offset in buffer at which to
 /// begin copying bytes to the current <see cref="T:OpenMcdf.CFStream">CFStream</see>. </param>
 /// <param name="count">The number of bytes to be written to the current <see cref="T:OpenMcdf.CFStream">CFStream</see> </param>
 /// <remarks>Current stream will be extended to receive data buffer over
 /// its current size.</remarks>
 internal void Write(byte[] data, long position, int offset, int count)
 {
     CheckDisposed();
     CompoundFile.WriteData(this, data, position, offset, count);
 }
        public void Test_CorruptedSectorChain_Cfs()
        {
            var f = new CompoundFile("corrupted-sector-chain.cfs");

            f.Close();
        }
Example #43
0
        void CMConvert(CompoundFile cf)
        {
            IList <IDirectoryEntry> entries = cf.GetDirectories();

            // extract Circuit maker files and then try and rename directories
            // to match .pcbdoc entries
            string CurrentDir = "";

            foreach (var entry in entries)
            {
                if (false && entry.Name == "Root Entry")
                {
                    DirectoryInfo Info = Directory.CreateDirectory(entry.Name);
                    if (!Info.Exists)
                    {
                        // for some reason the create directory failed so try again
                        Info = Directory.CreateDirectory(entry.Name);
                    }
                    Thread.Sleep(500); // TODO this is a frig sort out
                    ClearFolder(entry.Name);
                    Directory.SetCurrentDirectory(entry.Name);
                    CurrentDir = entry.Name;
                }
                else
                {
                    if (entry.StgType == StgType.StgStorage)
                    {
                        CurrentDir = entry.Name;
                        //                  Directory.CreateDirectory(entry.Name);
                        CFStorage storage    = cf.RootStorage.TryGetStorage(entry.Name);
                        CFStream  datastream = storage.GetStream("Data");
                        // get file contents and write to file
                        byte[] data = datastream.GetData();
                        if (data.Length == 0)
                        {
                            OutputString($"Deleted '{CurrentDir}' no data");
                            // remove empty directory
                            //                     Directory.Delete(CurrentDir);
                        }
                        else
                        {
                            // create the file
                            //                        File.WriteAllBytes(CurrentDir + "\\" + "Data.dat", data);
                            // now try and determine which file it is by examining the contents
                            TextFile   textfile   = ByteArrayToStructure <TextFile>(data);
                            TypeBinary typebinary = ByteArrayToStructure <TypeBinary>(data);
                            TextFile2  textfile2  = ByteArrayToStructure <TextFile2>(data);
                            if (IsPads(data))
                            {
                                RenameDirectory(CurrentDir, "Pads6", data);
                            }
                            else
                            if (IsVias(data))
                            {
                                RenameDirectory(CurrentDir, "Vias6", data);
                            }
                            else
                            if (IsTracks(data))
                            {
                                RenameDirectory(CurrentDir, "Tracks6", data);
                            }
                            else
                            if (IsComponentBodies(data))
                            {
                                RenameDirectory(CurrentDir, "ComponentBodies6", data);
                            }
                            else
                            if (IsBoard6(data))
                            {
                                RenameDirectory(CurrentDir, "Board6", data);
                            }
                            else
                            if (IsPolygons6(data))
                            {
                                RenameDirectory(CurrentDir, "Polygons6", data);
                            }
                            else
                            if (IsShapeBasedComponentBodies6(data))
                            {
                                RenameDirectory(CurrentDir, "ShapeBasedComponentBodies6", data);
                            }
                            else
                            if (IsArcs6(data))
                            {
                                RenameDirectory(CurrentDir, "Arcs6", data);
                            }
                            else
                            if (IsTexts6(data))
                            {
                                RenameDirectory(CurrentDir, "Texts6", data);
                            }
                            else
                            if (IsDimensions6(data))
                            {
                                RenameDirectory(CurrentDir, "Dimensions6", data);
                            }
                            else
                            if (IsRules6(data))
                            {
                                RenameDirectory(CurrentDir, "Rules6", data);
                            }
                            else
                            if (IsModels6(data))
                            {
                                RenameDirectory(CurrentDir, "Models", data);
                                // now need to get all of the model files
                                CFStream models;
                                byte[]   modeldata;
                                int      i = 0;
                                while ((models = storage.TryGetStream($"{i}")) != null)
                                {
                                    OutputString($"Creating {i}.dat model file");
                                    // get file contents and write to file
                                    modeldata = models.GetData();
                                    // uncompress the x.dat file to a .step file
                                    // step file is renamed to it's actual name later in the process
                                    //                 string Inflated = ZlibCodecDecompress(modeldata);
                                    //                 File.WriteAllText($"Models\\{i}.step", Inflated);
                                    i++;
                                }
                            }
                            else
                            if ((textfile2.type == 0x0001 && textfile2.Length < data.Length) || textfile.Length < data.Length)
                            {
                                // could be text file
                                string str = Encoding.Default.GetString(data);
                                if (str.Contains("ORIGINX"))
                                {
                                    RenameDirectory(CurrentDir, "Board6", data);
                                }
                                else
                                if (str.Contains("AdvancedPlacerOptions"))
                                {
                                    RenameDirectory(CurrentDir, "Advanced Placer Options6", data);
                                }
                                else
                                if (str.Contains("SUPERCLASS"))
                                {
                                    RenameDirectory(CurrentDir, "Classes6", data);
                                }
                                else
                                if (str.Contains("SOURCEFOOTPRINTLIBRARY"))
                                {
                                    RenameDirectory(CurrentDir, "Components6", data);
                                }
                                else
                                if (str.Contains("DesignRuleCheckerOptions"))
                                {
                                    RenameDirectory(CurrentDir, "Design Rule Checker Options6", data);
                                }
                                else
                                if (str.Contains("POSITIVENETNAME"))
                                {
                                    RenameDirectory(CurrentDir, "DifferentialPairs6", data);
                                }
                                else
                                if (str.Contains("FWDMSG"))
                                {
                                    RenameDirectory(CurrentDir, "FileVersionInfo", data);
                                }
                                else
                                if (str.Contains("LOOPREMOVAL="))
                                {
                                    RenameDirectory(CurrentDir, "Nets6", data);
                                }
                                else
                                if (str.Contains("PinSwapOptions"))
                                {
                                    RenameDirectory(CurrentDir, "Pin Swap Option6", data);
                                }
                                else
                                if (str.Contains("REMOVEDEAD"))
                                {
                                    RenameDirectory(CurrentDir, "Polygons6", data);
                                }
                                else
                                {
                                    OutputError($"Failed to convert possible text file '{CurrentDir}'");
                                }
                            }
                            else if (typebinary.Next < data.Length)
                            {
                                if (typebinary.Type == 0x03)
                                {
                                    RenameDirectory(CurrentDir, "Vias6", data);
                                }
                                else
                                if (typebinary.Type == 0x04)
                                {
                                    RenameDirectory(CurrentDir, "Tracks6", data);
                                }
                                else
                                if (typebinary.Type == 0x0B)
                                {
                                    RenameDirectory(CurrentDir, "Regions6", data);
                                }
                                else
                                if (typebinary.Type == 0x06)
                                {
                                    RenameDirectory(CurrentDir, "Fills6", data);
                                }
                                else
                                {
                                    OutputError($"Failed to convert possible binary file '{CurrentDir}'");
                                }
                            }
                        }
                    }

                    /*
                     * else
                     * if (entry.StgType == StgType.StgStream)
                     * {
                     *  CFStream stream = cf.RootStorage.TryGetStream(CurrentDir + "\\" + entry.Name);
                     *  if (stream != null && stream.Size != 0)
                     *  {
                     *      var data = new byte[stream.Size];
                     *      stream.Read(data, 0, data.Length);
                     *      File.WriteAllBytes(CurrentDir + "\\" + entry.Name, data);
                     *  }
                     * }
                     */
                }
                //    cf.RootStorage..DirEntry.EntryName.
                //OutputString($"{entry.ToString()}");
            }
            Directory.SetCurrentDirectory("..");
        }
        public void Test_CorruptedSectorChain_Doc2()
        {
            var f = new CompoundFile("corrupted-sector-chain-2.doc");

            f.Close();
        }
Example #45
0
 /// <summary>
 /// Read <paramref name="count"/> bytes associated with the stream object, starting from
 /// a provided <paramref name="position"/>. Method returns the effective count of bytes
 /// read.
 /// </summary>
 /// <param name="buffer">Array of bytes that will contain stream data</param>
 /// <param name="position">The zero-based byte position in the stream at which to begin reading
 /// the data from.</param>
 /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream. </param>
 /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
 /// <returns>The count of bytes effectively read</returns>
 /// <remarks>Method may read a number of bytes lesser then the requested one.</remarks>
 /// <code>
 ///  CompoundFile cf = null;
 ///  byte[] b = Helpers.GetBuffer(1024 * 2, 0xAA); //2MB buffer
 ///  CFStream item = cf.RootStorage.GetStream("AStream");
 ///
 ///  cf = new CompoundFile("$AFILENAME.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.Default);
 ///  item = cf.RootStorage.GetStream("AStream");
 ///
 ///  byte[] buffer = new byte[2048];
 ///  item.Read(buffer, 0, 2048);
 ///  Assert.IsTrue(Helpers.CompareBuffer(b, buffer));
 /// </code>
 ///
 /// <exception cref="T:OpenMcdf.CFDisposedException">
 /// Raised when the owner compound file has been closed.
 /// </exception>
 internal int Read(byte[] buffer, long position, int offset, int count)
 {
     CheckDisposed();
     return(CompoundFile.ReadData(this, position, buffer, offset, count));
 }
        public void Test_FUNCTIONAL_BEHAVIOUR()
        {
            //System.Diagnostics.Trace.Listeners.Add(new ConsoleTraceListener());

            const int N_FACTOR = 1;

            byte[] bA    = Helpers.GetBuffer(20 * 1024 * N_FACTOR, 0x0A);
            byte[] bB    = Helpers.GetBuffer(5 * 1024, 0x0B);
            byte[] bC    = Helpers.GetBuffer(5 * 1024, 0x0C);
            byte[] bD    = Helpers.GetBuffer(5 * 1024, 0x0D);
            byte[] bE    = Helpers.GetBuffer(8 * 1024 * N_FACTOR + 1, 0x1A);
            byte[] bF    = Helpers.GetBuffer(16 * 1024 * N_FACTOR, 0x1B);
            byte[] bG    = Helpers.GetBuffer(14 * 1024 * N_FACTOR, 0x1C);
            byte[] bH    = Helpers.GetBuffer(12 * 1024 * N_FACTOR, 0x1D);
            byte[] bE2   = Helpers.GetBuffer(8 * 1024 * N_FACTOR, 0x2A);
            byte[] bMini = Helpers.GetBuffer(1027, 0xEE);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            //############

            // Phase 1
            var cf = new CompoundFile(CFSVersion.Ver_3, CFSConfiguration.SectorRecycle);

            cf.RootStorage.AddStream("A").SetData(bA);
            cf.Save("OneStream.cfs");
            cf.Close();

            // Test Phase 1
            var      cfTest = new CompoundFile("OneStream.cfs");
            CFStream testSt = cfTest.RootStorage.GetStream("A");

            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bA.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bA, testSt.GetData()));

            cfTest.Close();

            //###########

            //Phase 2
            cf = new CompoundFile("OneStream.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle);

            cf.RootStorage.AddStream("B").SetData(bB);
            cf.RootStorage.AddStream("C").SetData(bC);
            cf.RootStorage.AddStream("D").SetData(bD);
            cf.RootStorage.AddStream("E").SetData(bE);
            cf.RootStorage.AddStream("F").SetData(bF);
            cf.RootStorage.AddStream("G").SetData(bG);
            cf.RootStorage.AddStream("H").SetData(bH);

            cf.Save("8_Streams.cfs");
            cf.Close();

            // Test Phase 2


            cfTest = new CompoundFile("8_Streams.cfs");

            testSt = cfTest.RootStorage.GetStream("B");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bB.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bB, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("C");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bC.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bC, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("D");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bD.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bD, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("E");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bE.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bE, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("F");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bF.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bF, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("G");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bG.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bG, testSt.GetData()));

            testSt = cfTest.RootStorage.GetStream("H");
            Assert.IsNotNull(testSt);
            Assert.IsTrue(testSt.Size == bH.Length);
            Assert.IsTrue(Helpers.CompareBuffer(bH, testSt.GetData()));

            cfTest.Close();


            File.Copy("8_Streams.cfs", "6_Streams.cfs", true);
            File.Delete("8_Streams.cfs");

            //###########
            //
#if !NETCOREAPP2_0
            Trace.Listeners.Add(new ConsoleTraceListener());
#endif
            // Phase 3
            cf = new CompoundFile("6_Streams.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle | CFSConfiguration.EraseFreeSectors);
            cf.RootStorage.Delete("D");
            cf.RootStorage.Delete("G");
            cf.Commit();

            cf.Close();

            //Test Phase 3


            cfTest = new CompoundFile("6_Streams.cfs");


            bool catched = false;

            try
            {
                testSt = cfTest.RootStorage.GetStream("D");
            }
            catch (Exception ex)
            {
                if (ex is CFItemNotFound)
                {
                    catched = true;
                }
            }

            Assert.IsTrue(catched);

            catched = false;

            try
            {
                testSt = cfTest.RootStorage.GetStream("G");
            }
            catch (Exception ex)
            {
                if (ex is CFItemNotFound)
                {
                    catched = true;
                }
            }

            Assert.IsTrue(catched);

            cfTest.Close();

            //##########

            // Phase 4

            File.Copy("6_Streams.cfs", "6_Streams_Shrinked.cfs", true);
            CompoundFile.ShrinkCompoundFile("6_Streams_Shrinked.cfs");

            // Test Phase 4

            Assert.IsTrue(new FileInfo("6_Streams_Shrinked.cfs").Length < new FileInfo("6_Streams.cfs").Length);

            cfTest = new CompoundFile("6_Streams_Shrinked.cfs");
            Action <CFItem> va = delegate(CFItem item)
            {
                if (item.IsStream)
                {
                    CFStream ia = item as CFStream;
                    Assert.IsNotNull(ia);
                    Assert.IsTrue(ia.Size > 0);
                    byte[] d = ia.GetData();
                    Assert.IsNotNull(d);
                    Assert.IsTrue(d.Length > 0);
                    Assert.IsTrue(d.Length == ia.Size);
                }
            };

            cfTest.RootStorage.VisitEntries(va, true);
            cfTest.Close();

            //##########

            //Phase 5

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStream("ZZZ").SetData(bF);
            cf.RootStorage.GetStream("E").Append(bE2);
            cf.Commit();
            cf.Close();


            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.CLSID = new Guid("EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStorage("MyStorage").AddStream("ZIP").Append(bE);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.AddStorage("AnotherStorage").AddStream("ANS").Append(bE);
            cf.RootStorage.Delete("MyStorage");


            cf.Commit();
            cf.Close();

            //Test Phase 5

            //#####

            //Phase 6

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            CFStorage root = cf.RootStorage;

            root.AddStorage("MiniStorage").AddStream("miniSt").Append(bMini);

            cf.RootStorage.GetStorage("MiniStorage").AddStream("miniSt2").Append(bMini);
            cf.Commit();
            cf.Close();

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            cf.RootStorage.GetStorage("MiniStorage").Delete("miniSt");


            cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Append(bE);

            cf.Commit();
            cf.Close();

            //Test Phase 6

            cfTest = new CompoundFile("6_Streams_Shrinked.cfs");
            byte[] d2 = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").GetData();
            Assert.IsTrue(d2.Length == (bE.Length + bMini.Length));

            int    cnt = 1;
            byte[] buf = new byte[cnt];
            cnt = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Read(buf, bMini.Length, cnt);

            Assert.IsTrue(cnt == 1);
            Assert.IsTrue(buf[0] == 0x1A);

            cnt = 1;
            cnt = cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").Read(buf, bMini.Length - 1, cnt);
            Assert.IsTrue(cnt == 1);
            Assert.IsTrue(buf[0] == 0xEE);

            try
            {
                cfTest.RootStorage.GetStorage("MiniStorage").GetStream("miniSt");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is CFItemNotFound);
            }

            cfTest.Close();

            //##############

            //Phase 7

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);

            cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").SetData(bA);
            cf.Commit();
            cf.Close();


            //Test Phase 7

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.Update, CFSConfiguration.SectorRecycle);
            d2 = cf.RootStorage.GetStorage("MiniStorage").GetStream("miniSt2").GetData();
            Assert.IsNotNull(d2);
            Assert.IsTrue(d2.Length == bA.Length);

            cf.Close();

            //##############

            cf = new CompoundFile("6_Streams_Shrinked.cfs", CFSUpdateMode.ReadOnly, CFSConfiguration.SectorRecycle);

            var myStream = cf.RootStorage.GetStream("C");
            var data     = myStream.GetData();
            Console.WriteLine(data[0] + " : " + data[data.Length - 1]);

            myStream = cf.RootStorage.GetStream("B");
            data     = myStream.GetData();
            Console.WriteLine(data[0] + " : " + data[data.Length - 1]);

            cf.Close();

            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
Example #47
0
        /// <summary>
        /// Get all the data associated with the stream object.
        /// </summary>
        /// <example>
        /// <code>
        ///     CompoundFile cf2 = new CompoundFile("AFileName.cfs");
        ///     CFStream st = cf2.RootStorage.GetStream("MyStream");
        ///     byte[] buffer = st.ReadAll();
        /// </code>
        /// </example>
        /// <returns>Array of byte containing stream data</returns>
        /// <exception cref="T:OpenMcdf.CFDisposedException">
        /// Raised when the owner compound file has been closed.
        /// </exception>
        public byte[] GetData()
        {
            CheckDisposed();

            return(CompoundFile.GetData(this));
        }
Example #48
0
 public void Test_CORRUPTEDDOC_BUG36_SHOULD_THROW_CORRUPTED_FILE_EXCEPTION()
 {
     using (CompoundFile file = new CompoundFile("CorruptedDoc_bug36.doc", CFSUpdateMode.ReadOnly, CFSConfiguration.NoValidationException)) {
         //Many thanks to theseus for bug reporting
     }
 }
Example #49
0
        public void Test_VISIT_ENTRIES_CORRUPTED_FILE_VALIDATION_OFF_BUT_CAN_LOAD()
        {
            CompoundFile f = null;

            try
            {
                //Corrupted file has invalid children item sid reference
                f = new CompoundFile("CorruptedDoc_bug3547815_B.doc", UpdateMode.ReadOnly, false, false, true);
            }
            catch (Exception ex)
            {
                Assert.Fail("No exception has to be fired on creation due to lazy loading");
            }

            FileStream output = null;

            try
            {
                output = new FileStream("LogEntriesCorrupted_2.txt", FileMode.Create);


                using (TextWriter tw = new StreamWriter(output))
                {

                    VisitedEntryAction va = delegate(ICFItem item)
                    {
                        tw.WriteLine(item.Name);
                    };

                    f.RootStorage.VisitEntries(va, true);
                    tw.Flush();
                }
            }
            catch (Exception ex)
            {
                Assert.Fail("Fail is corrupted but it has to be loaded anyway by test design");
            }
            finally
            {
                if (output != null)
                    output.Close();


            }
        }
Example #50
0
        internal static void StressMemory()
        {
            const int N_LOOP  = 20;
            const int MB_SIZE = 10;

            byte[] b   = GetBuffer(1024 * 1024 * MB_SIZE); //2GB buffer
            byte[] cmp = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 };

            CompoundFile cf = new CompoundFile(CFSVersion.Ver_4, CFSConfiguration.Default);
            CFStream     st = cf.RootStorage.AddStream("MySuperLargeStream");

            cf.Save("LARGE.cfs");
            cf.Close();

            //Console.WriteLine("Closed save");
            //Console.ReadKey();

            cf = new CompoundFile("LARGE.cfs", CFSUpdateMode.Update, CFSConfiguration.Default);
            CFStream cfst = cf.RootStorage.GetStream("MySuperLargeStream");

            Stopwatch sw = new Stopwatch();

            sw.Start();
            for (int i = 0; i < N_LOOP; i++)
            {
                cfst.Append(b);
                cf.Commit(true);

                Console.WriteLine("     Updated " + i.ToString());
                //Console.ReadKey();
            }

            cfst.Append(cmp);
            cf.Commit(true);
            sw.Stop();


            cf.Close();

            Console.WriteLine(sw.Elapsed.TotalMilliseconds);
            sw.Reset();

            //Console.WriteLine(sw.Elapsed.TotalMilliseconds);

            //Console.WriteLine("Closed Transacted");
            //Console.ReadKey();

            cf = new CompoundFile("LARGE.cfs");
            int count = 8;

            sw.Reset();
            sw.Start();
            byte[] data = new byte[count];
            count = cf.RootStorage.GetStream("MySuperLargeStream").Read(data, b.Length * (long)N_LOOP, count);
            sw.Stop();
            Console.Write(count);
            cf.Close();

            Console.WriteLine("Closed Final " + sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
Example #51
0
        public void Test_DELETE_DIRECTORY()
        {
            String FILENAME = "MultipleStorage2.cfs";
            CompoundFile cf = new CompoundFile(FILENAME, UpdateMode.ReadOnly, false, false);

            ICFStorage st = cf.RootStorage.GetStorage("MyStorage");

            Assert.IsNotNull(st);

            st.Delete("AnotherStorage");

            cf.Save("MultipleStorage_Delete.cfs");

            cf.Close();
        }
Example #52
0
        private void viewDataButton_Click(object sender, EventArgs e)
        {
            string errMessage;
            bool   checkRes = CheckDrives(out errMessage);

            if (!checkRes)
            {
                MainForm.ShowErrorFlexMessage(errMessage, "Внимание");
                return;
            }

            string filename = "";

            if (flashRButton.Checked)
            {
                string flashRoot = flashBox.Text.Substring(0, 1);
                filename = string.Format(@"{0}:\\Государственный пенсионный фонд ПМР\{1}.{2}\edatacon.pfs",
                                         flashRoot, _organization.regnumVal, _repYear);
            }
            else if (internetRButton.Checked)
            {
                filename = Path.Combine(Path.GetTempPath(), Settings.Default.TempFolder);
                filename = Path.Combine(filename, "edatacon.pfs");
            }

            try
            {
                if (!ReadDisk(out errMessage))
                {
                    MainForm.ShowWarningMessage(errMessage, "Внимание");
                }
            }
            catch
            {
                if (cdRButton.Checked)
                {
                    errMessage = "Не удалось считать ключевые данные с диска!\nВозможно Вы вставили неверный диск.";
                }
                else
                {
                    errMessage = "Не удалось считать ключевые данные с файла!\nВозможно Вы вставили неверный файл.";
                }
                MainForm.ShowWarningMessage(errMessage, "Внимание");
                return;
            }


            if (!File.Exists(filename))
            {
                MainForm.ShowInfoMessage("Сначала необходимо сформировать электронный файл для обмена с ЕГФСС",
                                         "Внимание");
                return;
            }

            if (_container != null)
            {
                _container.Close();
            }
            _container = new CompoundFile(filename);
            CFStream mapStream = _container.RootStorage.GetStream("map");

            byte[] mapBytes = Storage.DecryptStream(mapStream, _diskKey, _diskTable);
            //string mapStr = Encoding.GetEncoding(1251).GetString(mapBytes);
            CFStorage stylesDir      = _container.RootStorage.GetStorage("styles");
            CFStream  mapStyleStream = stylesDir.GetStream("map_style");

            byte[] mapStyleBytes = Storage.DecryptStream(mapStyleStream, _diskKey, _diskTable);
            //string styleStr = Encoding.GetEncoding(1251).GetString(mapStyleBytes);
            _container.Close();

            OrgPropXml props    = CfProperties.ReadProperty(filename);
            string     propHtml = props.GetHTML();

            string htmlStr;

            try
            {
                htmlStr = MapXml.GetHTML(mapBytes, mapStyleBytes);
            }
            catch (XsltException ex)
            {
                #region Текст сообщения всплывающего сообщения

                MainForm.ShowWarningFlexMessage(
                    "Электронный контейнер был сформирован программой версси 3.2.06 или ниже.\nБудет использован файл стиля из текущей версии программы.\n" +
                    ex.Message, "Внимание");

                #endregion

                htmlStr = MapXml.GetHTML(mapBytes);
            }
            catch (Exception ex)
            {
                MainForm.ShowWarningFlexMessage(ex.Message, "Необработанная ошибка");
                htmlStr = MapXml.GetHTML(mapBytes);
            }
            WebBrowser reportWb = new WebBrowser();
            htmlStr = htmlStr.Replace("<DIV class=\"insert_here\" />", propHtml);
            reportWb.DocumentText = htmlStr;
            MyPrinter.ShowWebPage(reportWb);
            reportWb.Navigating += new WebBrowserNavigatingEventHandler(reportWB_Navigating);
        }
Example #53
0
        public void Test_CHECK_DISPOSED_()
        {
            const String FILENAME = "MultipleStorage.cfs";
            CompoundFile cf = new CompoundFile(FILENAME);

            ICFStorage st = cf.RootStorage.GetStorage("MyStorage");
            cf.Close();

            try
            {
                byte[] temp = st.GetStream("MyStream").GetData();
                Assert.Fail("Stream without media");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is CFDisposedException);
            }
        }
Example #54
0
        /// <summary>
        /// Remove an entry from the current storage and compound file.
        /// </summary>
        /// <param name="entryName">The name of the entry in the current storage to delete</param>
        /// <example>
        /// <code>
        /// cf = new CompoundFile("A_FILE_YOU_CAN_CHANGE.cfs", UpdateMode.Update, true, false);
        /// cf.RootStorage.Delete("AStream"); // AStream item is assumed to exist.
        /// cf.Commit(true);
        /// cf.Close();
        /// </code>
        /// </example>
        /// <exception cref="T:OpenMcdf.CFDisposedException">Raised if trying to delete item from a closed compound file</exception>
        /// <exception cref="T:OpenMcdf.CFItemNotFound">Raised if item to delete is not found</exception>
        /// <exception cref="T:OpenMcdf.CFException">Raised if trying to delete root storage</exception>
        public void Delete(string entryName)
        {
            CheckDisposed();

            // Find entry to delete
            var tmp = DirectoryEntry.Mock(entryName, StgType.StgInvalid);

            Children.TryLookup(tmp, out var foundObj);

            if (foundObj == null)
            {
                throw new CFItemNotFound("Entry named [" + entryName + "] was not found");
            }

            if (((IDirectoryEntry)foundObj).StgType == StgType.StgRoot)
            {
                throw new CFException("Root storage cannot be removed");
            }

            IRbNode altDel;

            // ReSharper disable once SwitchStatementMissingSomeCases
            switch (((IDirectoryEntry)foundObj).StgType)
            {
            case StgType.StgStorage:

                var temp = new CFStorage(CompoundFile, ((IDirectoryEntry)foundObj));

                // This is a storage. we have to remove children items first
                foreach (var de in temp.Children)
                {
                    if (de is IDirectoryEntry ded)
                    {
                        temp.Delete(ded.Name);
                    }
                }


                // ...then we need to re-thread the root of siblings tree...
                DirEntry.Child = (Children.Root as IDirectoryEntry)?.SID ?? DirectoryEntry.nostream;

                // ...and finally Remove storage item from children tree...
                Children.Delete(foundObj, out altDel);

                // ...and remove directory (storage) entry

                if (altDel != null)
                {
                    foundObj = altDel;
                }

                CompoundFile.InvalidateDirectoryEntry(((IDirectoryEntry)foundObj).SID);

                break;

            case StgType.StgStream:

                // Free directory associated data stream.
                CompoundFile.FreeAssociatedData((foundObj as IDirectoryEntry).SID);

                // Remove item from children tree
                Children.Delete(foundObj, out altDel);

                // Re-thread the root of siblings tree...
                DirEntry.Child = (Children.Root as IDirectoryEntry)?.SID ?? DirectoryEntry.nostream;

                // Delete operation could possibly have cloned a directory, changing its SID.
                // Invalidate the ACTUALLY deleted directory.
                if (altDel != null)
                {
                    foundObj = altDel;
                }

                CompoundFile.InvalidateDirectoryEntry(((IDirectoryEntry)foundObj).SID);

                break;
            }
        }
Example #55
0
        public void Test_EXISTS_STORAGE_METHOD()
        {
            CompoundFile cf = new CompoundFile();

            Assert.IsFalse(cf.RootStorage.ExistsStorage("AStorageName"));
            cf.RootStorage.AddStorage("AStorageName");
            Assert.IsTrue(cf.RootStorage.ExistsStorage("AStorageName"));
        }
Example #56
0
 /// <summary>
 /// LoadFromCompoundStorageFile
 /// </summary>
 /// <param name="inStream"></param>
 /// <param name="excelSheetIndex"></param>
 /// <param name="password"></param>
 private void LoadFromCompoundStorage(Stream inStream, int excelSheetIndex, string password)
 {
     if (inStream != null)
     {
         try
         {
             CompoundFile file = new CompoundFile(true);
             if (!file.Read(inStream))
             {
                 this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("biffEntryError"), ExcelWarningCode.CannotOpen));
             }
             else
             {
                 file.RemoveStorage(XlsDirectoryEntryNames.XmlSignaturesStorage, "Root Entry");
                 if (this._documentInfo != null)
                 {
                     if (file.HasStream(XlsDirectoryEntryNames.SummaryInformationStream, "Root Entry"))
                     {
                         this._documentInfo.SummaryInformation = SummaryInformation.Read(file.GetStream(XlsDirectoryEntryNames.SummaryInformationStream));
                     }
                     if (file.HasStream(XlsDirectoryEntryNames.DocumentSummaryInfomationStream, "Root Entry"))
                     {
                         this._documentInfo.DocumentSummaryInfomation = DocumentSummaryInfomation.Read(file.GetStream(XlsDirectoryEntryNames.DocumentSummaryInfomationStream));
                     }
                 }
                 if (!file.HasStream(XlsDirectoryEntryNames.WorkbookStream, "Root Entry"))
                 {
                     this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("biffEntryError"), ExcelWarningCode.CannotOpen));
                     this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("biffEntryError"), ExcelWarningCode.CannotOpen));
                 }
                 else
                 {
                     Stream stream = (Stream) new MemoryStream(file.GetStream(XlsDirectoryEntryNames.WorkbookStream));
                     bool   flag   = this.IsEncryptedWorkbookStream(stream);
                     if (!flag && !string.IsNullOrWhiteSpace(password))
                     {
                         this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("invalidPassword"), ExcelWarningCode.IncorrectPassword));
                     }
                     else if (flag && (password == null))
                     {
                         this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("invalidPassword"), ExcelWarningCode.IncorrectPassword));
                     }
                     else if ((flag && (password != null)) && (password.Length > 0))
                     {
                         this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("winRTNotSupportPassword"), ExcelWarningCode.CannotOpen));
                     }
                     else if (flag && (password.Length == 0))
                     {
                         this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("invalidPassword"), ExcelWarningCode.IncorrectPassword));
                     }
                     else
                     {
                         new BiffRecordReader(this._excelReader, this._measure)
                         {
                             Password = password
                         }.ProcessStream(stream, excelSheetIndex);
                     }
                 }
             }
         }
         catch (Exception exception)
         {
             this._excelReader.OnExcelLoadError(new ExcelWarning(ResourceHelper.GetResourceString("biffGeneralError"), ExcelWarningCode.General, -1, -1, -1, exception));
         }
     }
 }
Example #57
0
        /// <summary>
        /// Extracts all the embedded object from the Office Open XML <paramref name="inputFile"/> to the
        /// <see cref="outputFolder"/> and returns the files with full path as a list of strings
        /// </summary>
        /// <param name="inputFile">The Office Open XML format file</param>
        /// <param name="embeddingPartString">The folder in the Office Open XML format (zip) file</param>
        /// <param name="outputFolder">The output folder</param>
        /// <returns>List with files or en empty list when there are nog embedded files</returns>
        /// <exception cref="OEFileIsPasswordProtected">Raised when the Microsoft Office file is password protected</exception>
        internal List <string> ExtractFromOfficeOpenXmlFormat(string inputFile, string embeddingPartString, string outputFolder)
        {
            var result = new List <string>();

            using (var inputFileMemoryStream = new MemoryStream(File.ReadAllBytes(inputFile)))
            {
                try
                {
                    var package = Package.Open(inputFileMemoryStream);

                    // Get the embedded files names.
                    foreach (var packagePart in package.GetParts())
                    {
                        if (packagePart.Uri.ToString().StartsWith(embeddingPartString))
                        {
                            using (var packagePartStream = packagePart.GetStream())
                                using (var packagePartMemoryStream = new MemoryStream())
                                {
                                    packagePartStream.CopyTo(packagePartMemoryStream);

                                    var fileName = outputFolder +
                                                   packagePart.Uri.ToString().Remove(0, embeddingPartString.Length);

                                    if (fileName.ToUpperInvariant().Contains("OLEOBJECT"))
                                    {
                                        using (var compoundFile = new CompoundFile(packagePartStream))
                                        {
                                            result.Add(Extraction.SaveFromStorageNode(compoundFile.RootStorage, outputFolder));
                                            //result.Add(ExtractFileFromOle10Native(packagePartMemoryStream.ToArray(), outputFolder));
                                        }
                                    }
                                    else
                                    {
                                        fileName = FileManager.FileExistsMakeNew(fileName);
                                        File.WriteAllBytes(fileName, packagePartMemoryStream.ToArray());
                                        result.Add(fileName);
                                    }
                                }
                        }
                    }
                    package.Close();

                    return(result);
                }
                catch (FileFormatException fileFormatException)
                {
                    if (
                        !fileFormatException.Message.Equals("File contains corrupted data.",
                                                            StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(null);
                    }

                    try
                    {
                        // When we receive this exception we can have 2 things:
                        // - The file is corrupt
                        // - The file is password protected, in this case the file is saved as a compound file
                        //EncryptedPackage
                        using (var compoundFile = new CompoundFile(inputFileMemoryStream))
                        {
                            if (compoundFile.RootStorage.ExistsStream("EncryptedPackage"))
                            {
                                throw new OEFileIsPasswordProtected("The file '" + Path.GetFileName(inputFile) +
                                                                    "' is password protected");
                            }
                        }
                    }
                    catch (Exception)
                    {
                        return(null);
                    }
                }
            }

            return(null);
        }
Example #58
0
 /// <summary>
 /// This method will extract and save the data from the given <see cref="CompoundFile"/> node to the <see cref="outputFolder"/>
 /// </summary>
 /// <param name="bytes">The <see cref="CompoundFile"/> as a byte array</param>
 /// <param name="outputFolder">The outputFolder</param>
 /// <param name="fileName">The fileName to use, null when the fileName is unknown</param>
 /// <returns></returns>
 /// <exception cref="OEFileIsPasswordProtected">Raised when a WordDocument, WorkBook or PowerPoint Document stream is password protected</exception>
 internal static string SaveFromStorageNode(byte[] bytes, string outputFolder, string fileName)
 {
     using (var memoryStream = new MemoryStream(bytes))
         using (var compoundFile = new CompoundFile(memoryStream))
             return(SaveFromStorageNode(compoundFile.RootStorage, outputFolder, fileName));
 }
Example #59
0
        public void Test_VISIT_ENTRIES()
        {
            const String STORAGE_NAME = "report.xls";
            CompoundFile cf = new CompoundFile(STORAGE_NAME);

            FileStream output = new FileStream("LogEntries.txt", FileMode.Create);
            TextWriter tw = new StreamWriter(output);

            VisitedEntryAction va = delegate(ICFItem item)
            {
                tw.WriteLine(item.Name);
            };

            cf.RootStorage.VisitEntries(va, true);

            tw.Close();

        }
Example #60
0
        /// <summary>
        /// Extracts all the embedded object from the OpenDocument <paramref name="inputFile"/> to the
        /// <see cref="outputFolder"/> and returns the files with full path as a list of strings
        /// </summary>
        /// <param name="inputFile">The OpenDocument format file</param>
        /// <param name="outputFolder">The output folder</param>
        /// <returns>List with files or en empty list when there are nog embedded files</returns>
        /// <exception cref="OEFileIsPasswordProtected">Raised when the OpenDocument format file is password protected</exception>
        internal List <string> ExtractFromOpenDocumentFormat(string inputFile, string outputFolder)
        {
            var result = new List <string>();

            var zipFile = new ZipFile(inputFile);

            // Check if the file is password protected
            var manifestEntry = zipFile.FindEntry("META-INF/manifest.xml", true);

            if (manifestEntry != -1)
            {
                using (var manifestEntryStream = zipFile.GetInputStream(manifestEntry))
                    using (var manifestEntryMemoryStream = new MemoryStream())
                    {
                        manifestEntryStream.CopyTo(manifestEntryMemoryStream);
                        manifestEntryMemoryStream.Position = 0;
                        using (var streamReader = new StreamReader(manifestEntryMemoryStream))
                        {
                            var manifest = streamReader.ReadToEnd();
                            if (manifest.ToUpperInvariant().Contains("ENCRYPTION-DATA"))
                            {
                                throw new OEFileIsPasswordProtected("The file '" + Path.GetFileName(inputFile) +
                                                                    "' is password protected");
                            }
                        }
                    }
            }

            foreach (ZipEntry zipEntry in zipFile)
            {
                if (!zipEntry.IsFile)
                {
                    continue;
                }
                if (zipEntry.IsCrypted)
                {
                    throw new OEFileIsPasswordProtected("The file '" + Path.GetFileName(inputFile) +
                                                        "' is password protected");
                }

                var name = zipEntry.Name.ToUpperInvariant();
                if (!name.StartsWith("OBJECT") || name.Contains("/"))
                {
                    continue;
                }

                string fileName = null;

                var objectReplacementFileIndex = zipFile.FindEntry("ObjectReplacements/" + name, true);
                if (objectReplacementFileIndex != -1)
                {
                    fileName = Extraction.GetFileNameFromObjectReplacementFile(zipFile, objectReplacementFileIndex);
                }

                using (var zipEntryStream = zipFile.GetInputStream(zipEntry))
                    using (var zipEntryMemoryStream = new MemoryStream())
                    {
                        zipEntryStream.CopyTo(zipEntryMemoryStream);

                        using (var compoundFile = new CompoundFile(zipEntryMemoryStream))
                            result.Add(Extraction.SaveFromStorageNode(compoundFile.RootStorage, outputFolder, fileName));
                    }
            }

            return(result);
        }