Ejemplo n.º 1
0
        internal static IFilter LoadAndInitIFilter(string fileName, string extension)
        {
            IFilter filter = LoadIFilter(extension);

            if (filter == null)
            {
                return(null);
            }

            IPersistFile persistFile = (filter as IPersistFile);

            if (persistFile != null)
            {
                persistFile.Load(fileName, 0);
                IFILTER_FLAGS flags;
                IFILTER_INIT  iflags =
                    IFILTER_INIT.CANON_HYPHENS |
                    IFILTER_INIT.CANON_PARAGRAPHS |
                    IFILTER_INIT.CANON_SPACES |
                    IFILTER_INIT.APPLY_INDEX_ATTRIBUTES |
                    IFILTER_INIT.HARD_LINE_BREAKS |
                    IFILTER_INIT.FILTER_OWNED_VALUE_OK;

                if (filter.Init(iflags, 0, IntPtr.Zero, out flags) == IFilterReturnCode.S_OK)
                {
                    return(filter);
                }
            }


            Marshal.ReleaseComObject(filter);
            return(null);
        }
Ejemplo n.º 2
0
        public void IUniformResourceLocatorTest()
        {
            using var tmp = new TempFile();

            // WRite it out
            var iUrl = new IUniformResourceLocator();

            Assert.That(() => iUrl.SetUrl(url), Throws.Nothing);
            IPersistFile ipf = null;

            Assert.That(ipf = iUrl as IPersistFile, Is.Not.Null);
            Assert.That(() => ipf.Save(tmp.FullName, false), Throws.Nothing);

            // Validate file
            var fi = new System.IO.FileInfo(tmp.FullName);

            Assert.That(fi.Length, Is.GreaterThan(10));

            // Read it back
            var          iUrl2 = new IUniformResourceLocator();
            IPersistFile ipf2  = null;

            Assert.That(ipf2 = iUrl2 as IPersistFile, Is.Not.Null);
            Assert.That(() => ipf2.Load(tmp.FullName, 0), Throws.Nothing);
            var url2 = string.Empty;

            Assert.That(() => iUrl2.GetUrl(out url2), Throws.Nothing);
            Assert.That(url2, Is.EqualTo(url));

            // Open it
            Assert.That(() => iUrl2.InvokeCommand(new URLINVOKECOMMANDINFO("open")), Throws.Nothing);
        }
Ejemplo n.º 3
0
 public void Load(string pszFileName)
 {
     // Get a pointer to the IPersistFile interface.
     ppf = (IPersistFile)psl;
     ppf.Load(pszFileName, 0);
     psl.Resolve(IntPtr.Zero, 0);
 }
Ejemplo n.º 4
0
            internal static DocHelper.IFilter LoadAndInitIFilter(string fileName, string extension)
            {
                DocHelper.IFilter filter = LoadIFilter(extension);
                if (filter == null)
                {
                    return(null);
                }

                IPersistFile persistFile = (filter as IPersistFile);

                if (persistFile != null)
                {
                    persistFile.Load(fileName, 0);
                    DocHelper.IFILTER_FLAGS flags;
                    DocHelper.IFILTER_INIT  iflags =
                        DocHelper.IFILTER_INIT.CANON_HYPHENS |
                        DocHelper.IFILTER_INIT.CANON_PARAGRAPHS |
                        DocHelper.IFILTER_INIT.CANON_SPACES |
                        DocHelper.IFILTER_INIT.APPLY_INDEX_ATTRIBUTES |
                        DocHelper.IFILTER_INIT.HARD_LINE_BREAKS |
                        DocHelper.IFILTER_INIT.FILTER_OWNED_VALUE_OK;

                    if (filter.Init(iflags, 0, IntPtr.Zero, out flags) == DocHelper.IFilterReturnCode.S_OK)
                    {
                        return(filter);
                    }
                }
                //If we failed to retreive an IPersistFile interface or to initialize
                //the filter, we release it and return null.
                Marshal.ReleaseComObject(filter);
                return(null);
            }
Ejemplo n.º 5
0
        private void Load(string path, int mode)
        {
            _handle.Load(path, mode);

            if (HasConsoleProperties)
            {
                ReadConsoleProperties();
            }
        }
Ejemplo n.º 6
0
        private static bool Run(string[] args)
        {
#if DEBUG
            Console.WriteLine("Attempting to create IShellItem for file {0}...", args[0]);
#endif
            IShellLink link = (IShellLink) new CShellLink();

            //Win32Shell.SHCreateItemFromParsingName(args[0], IntPtr.Zero, Win32Shell.IShellLinkId, out link);
            IPersistFile persistFileLink = (IPersistFile)link;
            if (persistFileLink.Load(args[0], 0x00000002L) != 0)
            {
                Console.WriteLine("Failed to load via IPersistFile.");
                return(false);
            }

            link.Resolve(IntPtr.Zero, 0);

            /*
             * link.SetPath("C:\\Windows\\notepad.exe");
             * link.SetArguments("");
             */

#if DEBUG
            Console.WriteLine("Querying for IPropertyStore interface...");
#endif
            IPropertyStore propStore = (IPropertyStore)link;

            try {
#if DEBUG
                Console.WriteLine("Attempting to set property 'System.AppUserModel.ID' to {0}...", args[1]);
#endif

                PropertyKey appUserModelKey = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);
                propStore.SetValue(ref appUserModelKey, new BStrWrapper(args[1]));
                propStore.Commit();

                //Store
                ((IPersistFile)link).Save(args[0], false);
            }
            catch (Exception ex) {
#if DEBUG
                throw;
#else
                Console.WriteLine("Unable to set value of AppUserModel.ID property.");
                Console.WriteLine(ex);

                return(false);
#endif
            }

            return(true);
        }
Ejemplo n.º 7
0
        private void LoadShortcut(string filePath)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("File path is not valid!");
            }

            if (!File.Exists(filePath))
            {
                throw new ArgumentException("File is not found! ( " + filePath + " )");
            }

            PersistFile.Load(filePath, STGM_READ);
        }
Ejemplo n.º 8
0
        internal SimpleFileLog(string absolutePath, int size)
        {
            // Open the log.
            // First, we try to open an existing log-- if that doesn't
            // work, we create a new one.
            //
            bool loaded = false;
            ILog log    = (ILog) new SimpleFileBasedLog();

            try
            {
                if (File.Exists(absolutePath))
                {
                    try
                    {
                        IPersistFile ipf = (IPersistFile)log;
                        ipf.Load(absolutePath, (int)STGM.ReadWrite);
                        loaded = true;
                    }
                    catch (FileNotFoundException)
                    {
                        // File not found, create a new one.
                    }
                }

                if (!loaded)
                {
                    // File does not exist.  Attempt to create a new one,
                    // with the specified size.
                    //
                    IFileBasedLogInit logInit = (IFileBasedLogInit)log;
                    logInit.InitNew(absolutePath, size);
                }

                log.SetAccessPolicyHint(RECORD_READING_POLICY.RANDOM);
                this.smuggledLog = new SmuggledIUnknown(log);
            }
            catch (COMException exception)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.ConvertKnownException(exception));
            }
            catch (FileNotFoundException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.Argument_FileNameInvalid)));
            }
            finally
            {
                SafeRelease(log);
            }
        }
Ejemplo n.º 9
0
        internal static bool IsMarkedRunAs(string shortcutFile)
        {
            Type         shellLinkType = Type.GetTypeFromCLSID(new Guid(ShellIIDGuid.CShellLink), true);
            IPersistFile shellFile     = Activator.CreateInstance(shellLinkType) as IPersistFile;

            if (shellFile != null)
            {
                shellFile.Load(shortcutFile, (int)AccessModes.Read);
                IShellLinkDataList shellLink = (IShellLinkDataList)shellFile;
                int flags;
                shellLink.GetFlags(out flags);

                return((flags & Convert.ToInt32(ShellLinkDataFlags.RunAs)) != 0);
            }

            return(false);
        }
Ejemplo n.º 10
0
        public static ShellLinkEx Load(string strLnkFilePath)
        {
            try
            {
                CShellLink csl = new CShellLink();

                IShellLinkW sl = (csl as IShellLinkW);
                if (sl == null)
                {
                    Debug.Assert(false); return(null);
                }
                IPersistFile pf = (csl as IPersistFile);
                if (pf == null)
                {
                    Debug.Assert(false); return(null);
                }

                pf.Load(strLnkFilePath, (int)(NativeMethods.STGM.Read |
                                              NativeMethods.STGM.ShareDenyWrite));

                const int ccMaxPath = KeePassLib.Native.NativeMethods.MAX_PATH;
                const int ccInfoTip = NativeMethods.INFOTIPSIZE;

                ShellLinkEx r = new ShellLinkEx();

                StringBuilder sb = new StringBuilder(ccMaxPath + 1);
                sl.GetPath(sb, sb.Capacity, IntPtr.Zero, 0);
                r.Path = sb.ToString();

                sb = new StringBuilder(ccInfoTip + 1);
                sl.GetArguments(sb, sb.Capacity);
                r.Arguments = sb.ToString();

                sb = new StringBuilder(ccInfoTip + 1);
                sl.GetDescription(sb, sb.Capacity);
                r.Description = sb.ToString();

                return(r);
            }
            catch (Exception) { Debug.Assert(false); }

            return(null);
        }
Ejemplo n.º 11
0
        public static IShellLink Load(IntPtr userInputHwnd, string existingLinkPath)
        {
            ShellLink    link        = new ShellLink();
            IShellLink   shellLink   = (IShellLink)link;
            IPersistFile persistFile = (IPersistFile)link;

            try
            {
                // load from disk
                persistFile.Load(existingLinkPath, (int)STGM.READ);

                // attempt to resolve a broken shortcut
                shellLink.Resolve(userInputHwnd, 0);
            }
            catch (Exception e)
            {
                ShellLogger.Error($"ShellLinkHelper: Unable to load link from path {existingLinkPath}", e);
            }

            return(shellLink);
        }
        public static HTMLDocumentClass LoadHtmlDocument(string htmlFile, int timeout)
        {
            HTMLDocumentClass doc = null;

            doc = new HTMLDocumentClass();
            //UCOMIPersistFile persistFile = (UCOMIPersistFile)doc;
            IPersistFile persistFile = (IPersistFile)doc;

            persistFile.Load(htmlFile, 0);
            int start = Environment.TickCount;

            while (string.CompareOrdinal(doc.readyState, "complete") != 0)
            {
                System.Windows.Forms.Application.DoEvents();
                if (Environment.TickCount - start > timeout)
                {
                    throw new Exception(string.Format("Error loading {0}. Timeout: {1}.", htmlFile, timeout));
                }
            }
            return(doc);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 指定したファイルからショートカットを読み込みます。
        /// </summary>
        /// <param name="linkFile">ショートカットを読み込むファイル</param>
        /// <param name="hWnd">このコードを呼び出したオーナーのウィンドウハンドル</param>
        /// <param name="resolveFlags">ショートカット情報の解決に関する動作を表すフラグ</param>
        /// <param name="timeOutMilliseconds">SLR_NO_UIを指定したときのタイムアウト値(ミリ秒)</param>
        /// <exception cref="FileNotFoundException">ファイルが見つかりません。</exception>
        /// <exception cref="COMException">IPersistFileインターフェイスを取得できませんでした。</exception>
        public void Load(string linkFile, IntPtr hWnd, ShellLinkResolveFlags resolveFlags, int timeOutMilliseconds)
        {
            if (!File.Exists(linkFile))
            {
                throw new FileNotFoundException("ファイルが見つかりません。", linkFile);
            }

            // IPersistFileインターフェイスを取得
            IPersistFile persistFile = GetIPersistFile();

            if (persistFile == null)
            {
                throw new COMException("IPersistFileインターフェイスを取得できませんでした。");
            }

            // 読み込み
            persistFile.Load(linkFile, 0x00000000);

            // フラグを処理
            uint flags = (uint)resolveFlags;

            if ((resolveFlags & ShellLinkResolveFlags.SLR_NO_UI) == ShellLinkResolveFlags.SLR_NO_UI)
            {
                flags |= (uint)(timeOutMilliseconds << 16);
            }

            // ショートカットに関する情報を読み込む
            if (isUnicodeEnvironment)
            {
                shellLinkW.Resolve(hWnd, flags);
            }
            else
            {
                shellLinkA.Resolve(hWnd, flags);
            }

            // カレントファイルを指定
            currentFile = linkFile;
        }
Ejemplo n.º 14
0
 private async void menuObjectFromFile_Click(object sender, EventArgs e)
 {
     try
     {
         using (OpenFileDialog dlg = new OpenFileDialog())
         {
             dlg.Filter = "All Files (*.*)|*.*";
             if (dlg.ShowDialog(this) == DialogResult.OK)
             {
                 COMCLSIDEntry entry = m_registry.GetFileClass(dlg.FileName);
                 if (entry != null)
                 {
                     IPersistFile ps = (IPersistFile)entry.CreateInstanceAsObject(entry.CreateContext, null);
                     ps.Load(dlg.FileName, (int)STGM.READ);
                     await HostObject(entry, ps, false);
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            if (args.Length == 2 && args[0] == "/get")
            {
                var          fp   = args[1];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READ);
                // http://8thway.blogspot.jp/2012/11/csharp-appusermodelid.html
                IPropertyStore pps = (IPropertyStore)plnk;
                PropVariant    v   = new PropVariant();
                pps.GetValue(ref AppUserModelIDKey, ref v);

                String s = "";
                if (v.vt == VT_BSTR)
                {
                    s = Marshal.PtrToStringUni(v.pVal);
                }
                if (v.vt == VT_LPWSTR)
                {
                    s = Marshal.PtrToStringUni(v.pVal);
                }

                Console.WriteLine(s);
            }
            else if (args.Length == 2 && args[0] == "/list")
            {
                var          fp   = args[1];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READ);
                IPropertyStore pps = (IPropertyStore)plnk;
                uint           cx;
                pps.GetCount(out cx);
                for (uint x = 0; x < cx; x++)
                {
                    PropertyKey k = new PropertyKey();
                    pps.GetAt(x, ref k);
                    PropVariant v = new PropVariant();
                    pps.GetValue(ref k, ref v);
                    String s = "";
                    if (v.vt == VT_BSTR)
                    {
                        s = Marshal.PtrToStringUni(v.pVal);
                    }
                    if (v.vt == VT_LPWSTR)
                    {
                        s = Marshal.PtrToStringUni(v.pVal);
                    }
                    Console.WriteLine(k.fmtid.ToString("B") + " " + k.pid + " " + v.vt + " " + s);
                }
            }
            else if (args.Length == 3 && args[0] == "/set")
            {
                var          fp   = args[1];
                var          s    = args[2];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READWRITE);
                // http://8thway.blogspot.jp/2012/11/csharp-appusermodelid.html
                IPropertyStore pps = (IPropertyStore)plnk;
                PropVariant    pv  = new PropVariant {
                    vt   = VT_LPWSTR,
                    pVal = Marshal.StringToBSTR(s)
                };
                pps.SetValue(ref AppUserModelIDKey, ref pv);
                pps.Commit();
                ppf.Save(fp, false);
            }
            else
            {
                helpYa();
            }
        }
Ejemplo n.º 16
0
        public void Load(string linkFileName)
        {
            if (null == linkFileName)
            {
                throw new ArgumentNullException("linkFileName", "A name of the link file cannot be null");
            }
            if (!File.Exists(linkFileName))
            {
                throw new FileNotFoundException("Link not found", linkFileName);
            }
            new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, linkFileName).Demand();

            object sl = null;

            try
            {
                Type slType = Type.GetTypeFromCLSID(CLSID_ShellLink);
                sl = Activator.CreateInstance(slType);
                IPersistFile pf = sl as IPersistFile;
                pf.Load(linkFileName, 0);

                int           showCmd;
                StringBuilder builder    = new StringBuilder(INFOTIPSIZE);
                IShellLinkW   shellLinkW = sl as IShellLinkW;
                if (null == shellLinkW)
                {
                    IShellLinkA shellLinkA = sl as IShellLinkA;
                    if (null == shellLinkA)
                    {
                        ThrowInvalidComObjectException();
                    }
                    shellLinkA.GetArguments(builder, builder.Capacity);
                    this.arguments = builder.ToString();
                    shellLinkA.GetDescription(builder, builder.Capacity);
                    this.description = builder.ToString();
                    shellLinkA.GetHotkey(out this.hotkey);
                    shellLinkA.GetIconLocation(builder, builder.Capacity, out this.iconIndex);
                    this.iconPath = builder.ToString();
                    Win32FindDataA wfd;
                    shellLinkA.GetPath(builder, builder.Capacity, out wfd, SLGP_UNCPRIORITY);
                    this.path = builder.ToString();
                    shellLinkA.GetShowCmd(out showCmd);
                    shellLinkA.GetWorkingDirectory(builder, builder.Capacity);
                    this.workingDirectory = builder.ToString();
                }
                else
                {
                    shellLinkW.GetArguments(builder, builder.Capacity);
                    this.arguments = builder.ToString();
                    shellLinkW.GetDescription(builder, builder.Capacity);
                    this.description = builder.ToString();
                    shellLinkW.GetHotkey(out this.hotkey);
                    shellLinkW.GetIconLocation(builder, builder.Capacity, out this.iconIndex);
                    this.iconPath = builder.ToString();
                    Win32FindDataW wfd;
                    shellLinkW.GetPath(builder, builder.Capacity, out wfd, SLGP_UNCPRIORITY);
                    this.path = builder.ToString();
                    shellLinkW.GetShowCmd(out showCmd);
                    shellLinkW.GetWorkingDirectory(builder, builder.Capacity);
                    this.workingDirectory = builder.ToString();
                }
                this.showCmd = (ShowCommand)showCmd;
            }
            finally
            {
                if (null != sl)
                {
                    Marshal.ReleaseComObject(sl);
                }
            }
            // This object is not eligible for the garbage collection during this method call
            GC.KeepAlive(this);
        }
Ejemplo n.º 17
0
        private static bool SetShortcut()
        {
            bool writeShortcut = false;

            PROPERTYKEY appModelIDKey = PROPERTYKEY.System.AppUserModel.ID;

            IShellLinkW    shortcut      = (IShellLinkW) new CShellLinkW();
            IPersistFile   persistFile   = (IPersistFile)shortcut;
            IPropertyStore propertyStore = (IPropertyStore)shortcut;

            try
            {
                persistFile.Load(LINKFILE_PATH, (int)Vanara.PInvoke.STGM.STGM_READ);
            }
            catch (System.IO.FileNotFoundException)
            {
                writeShortcut = true;

                // This is possibly first invocation so set registry in order to persist in Action Center
                ConfigureRegistry();
            }

            if (!writeShortcut)
            {
                StringBuilder curPath = new StringBuilder(Vanara.PInvoke.Kernel32.MAX_PATH);
                shortcut.GetPath(curPath, curPath.Capacity, null, SLGP.SLGP_RAWPATH);

                if (!EXE_PATH.Equals(curPath.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    writeShortcut = true;
                }
            }

            if (!writeShortcut)
            {
                StringBuilder curArgs = new StringBuilder(Vanara.PInvoke.ComCtl32.INFOTIPSIZE);
                shortcut.GetArguments(curArgs, curArgs.Capacity);

                if (!SHORTCUT_ARGUMENTS.Equals(curArgs.ToString(), StringComparison.Ordinal))
                {
                    writeShortcut = true;
                }
            }

            if (!writeShortcut)
            {
                using (PROPVARIANT pv = new PROPVARIANT())
                {
                    propertyStore.GetValue(ref appModelIDKey, pv);
                    if (!APP_ID.Equals(pv.pwszVal, StringComparison.Ordinal))
                    {
                        writeShortcut = true;
                    }
                }
            }

            if (writeShortcut)
            {
                shortcut.SetPath(EXE_PATH);
                shortcut.SetArguments(string.Empty);

                using (PROPVARIANT pv = new PROPVARIANT(APP_ID))
                {
                    propertyStore.SetValue(ref appModelIDKey, pv);
                    propertyStore.Commit();
                }

                persistFile.Save(LINKFILE_PATH, true);

                return(true);
            }

            return(false);
        }
Ejemplo n.º 18
0
 public void Load(string pszFileName)
 {
     // Get a pointer to the IPersistFile interface.
     ppf = (IPersistFile) psl;
     ppf.Load(pszFileName, 0);
     psl.Resolve(IntPtr.Zero, 0);
 }
Ejemplo n.º 19
0
        public string GetText(string discoveryPath)
        // path is the path of the .doc, .xls or .ppt  file
        // text is the variable in which all the extracted text will be stored
        {
            String result = "";
            int    count  = 0;

            IFilter ifilt = (IFilter)(new CFilter());

            try
            {
                //System.Runtime.InteropServices.UCOMIPersistFile ipf = (System.Runtime.InteropServices.UCOMIPersistFile)(ifilt);
                IPersistFile ipf = (IPersistFile)(ifilt);
                ipf.Load(discoveryPath, 0);
                uint       i  = 0;
                STAT_CHUNK ps = new STAT_CHUNK();
                ifilt.Init(IFILTER_INIT.NONE, 0, null, ref i);
                int hr = 0;

                while (hr == 0)
                {
                    ifilt.GetChunk(out ps);
                    if (ps.flags == CHUNKSTATE.CHUNK_TEXT)
                    {
                        uint pcwcBuffer = 1000;
                        int  hr2        = 0;
                        while (hr2 == Constants.FILTER_S_LAST_TEXT || hr2 == 0)
                        {
                            try
                            {
                                pcwcBuffer = 1000;
                                StringBuilder sbBuffer = new StringBuilder((int)pcwcBuffer);
                                hr2 = ifilt.GetText(ref pcwcBuffer, sbBuffer);
                                // Console.WriteLine(pcwcBuffer.ToString());
                                if (hr2 >= 0)
                                {
                                    result += sbBuffer.ToString(0, (int)pcwcBuffer);
                                }
                                //textBox1.Text +="\n";
                                // result += "#########################################";
                                count++;
                            }
                            catch (COMException myE)
                            {
                                Console.WriteLine(myE.Data + "\n" + myE.Message + "\n");
                            }
                        }
                    }
                }
            }
            catch (COMException myE)
            {
                Console.WriteLine(myE.Data + "\n" + myE.Message + "\n");
            }
            finally
            {
                Marshal.ReleaseComObject(ifilt);
            }

            return(result);
        }