public static extern SafeFindHandle FindFirstFileExW(
			string lpFileName,
			FINDEX_INFO_LEVELS fInfoLevelId,
			out WIN32_FIND_DATAW lpFindFileData,
			FINDEX_SEARCH_OPS fSearchOp,
			IntPtr lpSearchFilter,
			FINDEX_ADDITIONAL_FLAGS dwAdditionalFlags);
Ejemplo n.º 2
0
        public string ResolveShortcut(string filename)
        {
            ShellLink link = new ShellLink();

            ((IPersistFile)link).Load(filename, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            // ((IShellLinkW)link).Resolve(hwnd, 0)
            StringBuilder sbPath     = new StringBuilder(MAX_PATH);
            StringBuilder sbDesc     = new StringBuilder(MAX_PATH);
            StringBuilder sbArgs     = new StringBuilder(MAX_PATH);
            StringBuilder sbWorkDir  = new StringBuilder(MAX_PATH);
            StringBuilder sbIconLocn = new StringBuilder(MAX_PATH);
            int           iIconNum   = 0;


            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(sbPath, sbPath.Capacity, out data, 0);
            ((IShellLinkW)link).GetDescription(sbDesc, sbDesc.Capacity);
            ((IShellLinkW)link).GetArguments(sbArgs, sbDesc.Capacity);
            ((IShellLinkW)link).GetWorkingDirectory(sbWorkDir, sbWorkDir.Capacity);
            ((IShellLinkW)link).GetIconLocation(sbIconLocn, sbIconLocn.Capacity, out iIconNum);

            return(sbPath.ToString());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Init()
        {
            WIN32_FIND_DATAW findData   = new WIN32_FIND_DATAW();
            string           searchPath = Path.Combine(searchData.path, "*");

            handle = UnsafeNativeMethods.FindFirstFileExW(searchPath, infoLevel, findData, NativeEnums.FindExSearchOp.NameMatch, IntPtr.Zero, additionalFlags);

            if (handle.IsInvalid)
            {
                int error = Marshal.GetLastWin32Error();

                if (error != NativeConstants.ERROR_FILE_NOT_FOUND && error != NativeConstants.ERROR_NO_MORE_FILES)
                {
                    HandleError(error);
                }
                else
                {
                    // If no matching files are found exit when MoveNext is called.
                    // This may happen for an empty root directory.
                    state = STATE_FINISH;
                }
            }
            else
            {
                AddToVisitedDirectories(searchData.path);
                state = STATE_INIT;
                if (FirstFileIncluded(findData))
                {
                    current = CreateFilePath(findData);
                }
            }
        }
 public static extern SafeFindHandle FindFirstFileExW(
     string lpFileName,
     FINDEX_INFO_LEVELS fInfoLevelId,
     out WIN32_FIND_DATAW lpFindFileData,
     FINDEX_SEARCH_OPS fSearchOp,
     IntPtr lpSearchFilter,
     FINDEX_ADDITIONAL_FLAGS dwAdditionalFlags);
Ejemplo n.º 5
0
 private static extern SafeSearchHandle FindFirstFileEx(
     string lpFileName,
     FINDEX_INFO_LEVELS fInfoLevelId,
     out WIN32_FIND_DATAW lpFindFileData,
     FINDEX_SEARCH_OPS fSearchOp,
     IntPtr lpSearchFilter,
     int dwAdditionalFlags);
Ejemplo n.º 6
0
        public bool ResolveShortcut(string shortcut, out string filepath, out string arguments)
        {
            ShellLink link = new ShellLink();

            ((IPersistFile)link).Load(shortcut, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            // ((IShellLinkW)link).Resolve(hwnd, 0)
            StringBuilder    path = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(path, path.Capacity, out data, 0);

            StringBuilder args = new StringBuilder(MAX_PATH);

            ((IShellLinkW)link).GetArguments(args, args.Capacity);

            filepath  = path.ToString();
            arguments = args.ToString();

            if (!File.Exists(filepath))
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 7
0
        // Retrieve the target path using Shell Link
        public string retrieveTargetPath(string path)
        {
            var       link      = new ShellLink();
            const int STGM_READ = 0;

            ((IPersistFile)link).Load(path, STGM_READ);
            var hwnd = new _RemotableHandle();

            ((IShellLinkW)link).Resolve(ref hwnd, 0);

            const int     MAX_PATH = 260;
            StringBuilder buffer   = new StringBuilder(MAX_PATH);

            var data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH);
            var target = buffer.ToString();

            // To set the app description
            if (!String.IsNullOrEmpty(target))
            {
                buffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetDescription(buffer, MAX_PATH);
                description = buffer.ToString();
            }

            // To release unmanaged memory
            Marshal.ReleaseComObject(link);

            return(target);
        }
        private void Init()
        {
            WIN32_FIND_DATAW findData = new WIN32_FIND_DATAW();
            string searchPath = Path.Combine(searchData.path, "*");
            handle = UnsafeNativeMethods.FindFirstFileExW(
                searchPath,
                infoLevel,
                findData,
                NativeEnums.FindExSearchOp.NameMatch,
                IntPtr.Zero,
                additionalFlags);

            if (handle.IsInvalid)
            {
                handle.Dispose();
                handle = null;

                state = STATE_FINISH;
            }
            else
            {
                state = STATE_INIT;
                if (FirstFileIncluded(findData))
                {
                    current = CreateFilePath(findData);
                }
            }
        }
Ejemplo n.º 9
0
 public extern static System.IntPtr FindFirstFileTransactedW(
     [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)] string lpFileName,
     FINDEX_INFO_LEVELS fInfoLevelId,
     out WIN32_FIND_DATAW lpFindFileData,
     FINDEX_SEARCH_OPS fSearchOp,
     System.IntPtr lpSearchFilter,
     int dwAdditionalFlags,
     System.IntPtr hTransaction);
Ejemplo n.º 10
0
        /// <summary>
        /// Adds the directory to search list if it has not already been searched.
        /// </summary>
        /// <param name="findData">The find data.</param>
        private void AddDirectoryToSearchList(WIN32_FIND_DATAW findData)
        {
            string path = Path.Combine(searchData.path, findData.cFileName);

            if (IsNewDirectory(path))
            {
                searchDirectories.Enqueue(new SearchData(path));
            }
        }
Ejemplo n.º 11
0
        public static string ResolveShortcut(string pFileName)
        {
            ShellLink wLink = new ShellLink();

            ((IPersistFile)wLink).Load(pFileName, STGM_READ);
            StringBuilder    wPath = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW wData = new WIN32_FIND_DATAW();

            ((IShellLinkW)wLink).GetPath(wPath, wPath.Capacity, out wData, 0);
            return(wPath.ToString());
        }
Ejemplo n.º 12
0
        public static string ResolveShortcut(string filename)
        {
            ShellLink link = new ShellLink();

            ((IPersistFile)link).Load(filename, STGM_READ);
            StringBuilder    sb   = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
            return(sb.ToString());
        }
Ejemplo n.º 13
0
 private string CreateFilePath(WIN32_FIND_DATAW findData)
 {
     if (shellLinkTarget != null)
     {
         return shellLinkTarget;
     }
     else
     {
         return Path.Combine(searchData.path, findData.cFileName);
     }
 }
Ejemplo n.º 14
0
            public static string Resolve(string filename)
            {
                ShellLink link = new ShellLink();

                ((IPersistFile)link).Load(filename, STGM_READ);
                // If I can get hold of the hwnd call resolve first. This handles moved and renamed files.
                // ((IShellLinkW)link).Resolve(hwnd, 0)
                StringBuilder    sb   = new StringBuilder(MAX_PATH);
                WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

                ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
                return(sb.ToString());
            }
        public static string ResolveShortcut(string filename)
        {
            // this gets the full path from a shortcut (.lnk file).
            ShellLink link = new ShellLink();

            (( IPersistFile )link).Load(filename, STGM_READ);
            StringBuilder    sb   = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            (( IShellLinkW )link).GetPath(sb, sb.Capacity, out data, 0);
            string finalString = sb.ToString();

            if (finalString.Length == 0)
            {
                finalString = filename;
            }
            // If the the shortcut's target resolves to the Program Files or System32 directory, and the user is on a
            // 64-bit machine, the final string may actually point to C:\Program Files (x86) or C:\Windows\SYSWOW64.
            // This is due to File System Redirection in Windows -- http://msdn.microsoft.com/en-us/library/aa365743%28VS.85%29.aspx.
            // Unfortunately the solution there doesn't appear to work for 32-bit apps on 64-bit machines.
            // We will provide a workaround here:
            string newPath = ValidateShortcutPath(finalString, "SysWOW64", "System32");

            if (File.Exists(newPath) && !File.Exists(finalString))
            {
                // the file is actually stored in System32 instead of SysWOW64. Let's update it.
                finalString = newPath;
            }
            newPath = ValidateShortcutPath(finalString, "Program Files (x86)", "Program Files");
            if (File.Exists(newPath) && !File.Exists(finalString))
            {
                // the file is actually stored in Program Files instead of Program Files (x86). Let's update it.
                finalString = newPath;
            }
            // the lnk may incorrectly resolve to the C:\Windows\Installer directory. Check for this.
            if (finalString.ToLower().IndexOf("windows\\installer") > -1)
            {
                finalString = filename;
            }
            if (File.Exists(finalString))
            {
                return(finalString);
            }
            else
            {
                return(filename);
            }
        }
Ejemplo n.º 16
0
        private bool FirstFileIncluded(WIN32_FIND_DATAW findData)
        {
            if ((findData.dwFileAttributes & NativeConstants.FILE_ATTRIBUTE_DIRECTORY) == NativeConstants.FILE_ATTRIBUTE_DIRECTORY)
            {
                if (searchOption == SearchOption.AllDirectories && !findData.cFileName.Equals(".") && !findData.cFileName.Equals(".."))
                {
                    AddDirectoryToSearchList(findData);
                }
            }
            else
            {
                return(IsFileIncluded(findData));
            }

            return(false);
        }
Ejemplo n.º 17
0
        private bool FirstFileIncluded(WIN32_FIND_DATAW findData)
        {
            if ((findData.dwFileAttributes & NativeConstants.FILE_ATTRIBUTE_DIRECTORY) == NativeConstants.FILE_ATTRIBUTE_DIRECTORY)
            {
                if (searchOption == SearchOption.AllDirectories && !findData.cFileName.Equals(".") && !findData.cFileName.Equals(".."))
                {
                    searchDirectories.Enqueue(new SearchData(searchData, findData.cFileName));
                }
            }
            else
            {
                return IsFileIncluded(findData);
            }

            return false;
        }
Ejemplo n.º 18
0
        // Retrieve the target path using Shell Link
        public string RetrieveTargetPath(string path)
        {
            var       link      = new ShellLink();
            const int STGM_READ = 0;

            try
            {
                ((IPersistFile)link).Load(path, STGM_READ);
            }
            catch (System.IO.FileNotFoundException ex)
            {
                ProgramLogger.LogException($"|Win32| ShellLinkHelper.retrieveTargetPath | {path} | Path could not be retrieved", ex);
                return(String.Empty);
            }

            var hwnd = new _RemotableHandle();

            ((IShellLinkW)link).Resolve(ref hwnd, 0);

            const int     MAX_PATH = 260;
            StringBuilder buffer   = new StringBuilder(MAX_PATH);

            var data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH);
            var target = buffer.ToString();

            // To set the app description
            if (!String.IsNullOrEmpty(target))
            {
                buffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetDescription(buffer, MAX_PATH);
                description = buffer.ToString();

                StringBuilder argumentBuffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetArguments(argumentBuffer, argumentBuffer.Capacity);
                Arguments = argumentBuffer.ToString();

                // Set variable to true if the program takes in any arguments
                if (argumentBuffer.Length != 0)
                {
                    hasArguments = true;
                }
            }
            return(target);
        }
Ejemplo n.º 19
0
        public static string ResolveShortcut(string filename)
        {
            var link = new ShellLink();

            try
            {
                ((IPersistFile)link).Load(filename, STGM_READ);
                var sb   = new StringBuilder(MAX_PATH);
                var data = new WIN32_FIND_DATAW();
                ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
                return(sb.ToString());
            }
            finally
            {
                Marshal.FinalReleaseComObject(link);
            }
        }
Ejemplo n.º 20
0
        private static FileInformation PopulateFileInformation(WIN32_FIND_DATAW findData, String path)
        {
            FileInformation fileInformation = new FileInformation();

            fileInformation.FileAttribute  = Convert.ToUInt16(findData.dwFileAttributes);
            fileInformation.LastWriteTime  = findData.ftLastWriteTime.ToDateTime();
            fileInformation.LastAccessTime = findData.ftLastAccessTime.ToDateTime();
            fileInformation.CreationTime   = findData.ftCreationTime.ToDateTime();
            //nFileSizeHigh * (MAXDWORD + 1)) +nFileSizeLow -- from MS DOCS
            long DWORDMAX = UInt32.MaxValue;

            fileInformation.FileSize = (findData.nFileSizeHigh * (DWORDMAX + 1)) + findData.nFileSizeLow;
            path = path.EndsWith(@"\") ? path : path + @"\";
            fileInformation.FullPath = path + findData.cFileName;

            return(fileInformation);
        }
Ejemplo n.º 21
0
        public void FindFirstFile()
        {
            string           sys32Path = Environment.GetFolderPath(Environment.SpecialFolder.System);
            WIN32_FIND_DATAW data      = new WIN32_FIND_DATAW();
            IntPtr           handle    = NativeMethods.FindFirstFileW(Path.Combine(sys32Path, "n") + "*", out data);

            Assert.NotEqual(handle, IntPtr.Zero);
            List <string> list = new List <string>();

            list.Add(data.cFileName);
            while (NativeMethods.FindNextFileW(handle, out data))
            {
                list.Add(data.cFileName);
            }

            Assert.True(list.Count > 3);
            NativeMethods.FindClose(handle);
        }
Ejemplo n.º 22
0
        public static string Resolve(string filename)
        {
            #if !__MonoCS__
            ShellLink link = new ShellLink();
            ((IPersistFile)link).Load(filename, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            // ((IShellLinkW)link).Resolve(hwnd, 0)
            StringBuilder sb = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
            return sb.ToString();
            #else
            if (!SIL.IO.RobustFile.Exists(filename))
                return string.Empty;

            return SIL.IO.RobustFile.ReadAllText(filename);
            #endif
        }
Ejemplo n.º 23
0
        public static string Resolve(string filename)
        {
            // We can only resolve shortcuts on Windows
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                return(filename);
            }

            ShellLink link = new ShellLink();

            (link as IPersistFile).Load(filename, STGM_READ);

            StringBuilder    sb   = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            (link as IShellLinkW).GetPath(sb, sb.Capacity, out data, 0);

            return(sb.ToString());
        }
Ejemplo n.º 24
0
        public static string Resolve(string filename)
        {
#if !__MonoCS__
            ShellLink link = new ShellLink();
            ((IPersistFile)link).Load(filename, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            // ((IShellLinkW)link).Resolve(hwnd, 0)
            StringBuilder    sb   = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
            return(sb.ToString());
#else
            if (!SIL.IO.RobustFile.Exists(filename))
            {
                return(string.Empty);
            }

            return(SIL.IO.RobustFile.ReadAllText(filename));
#endif
        }
Ejemplo n.º 25
0
        internal static string GetPath(string filename)
        {
            string path = null;

            try
            {
                ShellLink link = new ShellLink();

                ((IPersistFile)link).Load(filename, STGM_READ);

                StringBuilder    sb   = new StringBuilder(MAX_PATH);
                WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
                ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);

                path = sb.ToString();
            }
            catch { }

            return(path);
        }
Ejemplo n.º 26
0
        private bool IsFileIncluded(WIN32_FIND_DATAW findData)
        {
            if (findData.cFileName.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase) && dereferenceLinks)
            {
                if (shellLink.Load(Path.Combine(searchData.path, findData.cFileName)))
                {
                    bool   isDirectory;
                    string target = ResolveShortcutTarget(shellLink.Path, out isDirectory);

                    if (!string.IsNullOrEmpty(target))
                    {
                        if (isDirectory)
                        {
                            if (IsNewDirectory(target))
                            {
                                // If the shortcut target is a directory, add it to the search list.
                                searchDirectories.Enqueue(new SearchData(target));
                            }
                        }
                        else if (FileMatchesFilter(target))
                        {
                            shellLinkTarget = target;
                            return(true);
                        }
                    }
                }
            }
            else if (FileMatchesFilter(findData.cFileName))
            {
                if (needsPathDiscoveryDemand)
                {
                    DoDemand(searchData.path);
                    needsPathDiscoveryDemand = false;
                }
                shellLinkTarget = null;

                return(true);
            }

            return(false);
        }
Ejemplo n.º 27
0
        private FileEntry GetFileEntry(string fullPath, WIN32_FIND_DATAW findData)
        {
            if (!_configuration.IncludeHidden && (findData.dwFileAttributes & (FileAttributes.System | FileAttributes.Hidden)) == (FileAttributes.System | FileAttributes.Hidden))
            {
                return(null);
            }

            var fileEntry = new FileEntry
            {
                Fullname = fullPath,
                Size     = ((long)findData.nFileSizeHigh << 0x20) | findData.nFileSizeLow
            };

            if (_configuration.IncludeFileDates)
            {
                fileEntry.Created  = Utils.FileTimeToDateTimeOffset(findData.ftCreationTime);
                fileEntry.Modified = Utils.FileTimeToDateTimeOffset(findData.ftLastWriteTime);
            }

            return(fileEntry);
        }
Ejemplo n.º 28
0
        public static bool ResolveShortcut(out string realFilePath, string linkFilePath)
        {
            realFilePath = "<invalid>";

            try
            {
                ShellLink link = new ShellLink();
                ((IPersistFile)link).Load(linkFilePath, STGM_READ);
                StringBuilder    sb   = new StringBuilder(MAX_PATH);
                WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
                ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);

                realFilePath = sb.ToString();
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 29
0
        public static ShortcutInfo ResolveShortcut(string filename)
        {
            ShellLink link = new ShellLink();

            ((IPersistFile)link).Load(filename, STGM_READ);

            var filePathStringBuilder = new StringBuilder(MAX_PATH);
            var data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(filePathStringBuilder, filePathStringBuilder.Capacity, out data, 0);

            StringBuilder argumentsStringBuilder = new StringBuilder(MAX_PATH);

            ((IShellLinkW)link).GetArguments(argumentsStringBuilder, MAX_PATH);

            return(new ShortcutInfo
            {
                Path = filePathStringBuilder.ToString(),
                Arguments = argumentsStringBuilder.ToString(),
            });
        }
Ejemplo n.º 30
0
        public static void ResolveShortcut(string filename, out string name, out string command, out string args, out string description, out string iconLocation, out int iconIndex)
        {
            ShellLink link = new ShellLink();

            ((IPersistFile)link).Load(filename, STGM_READ);
            //((IShellLinkW)link).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_ANY_MATCH);

            StringBuilder    sb   = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, SLGP_FLAGS.SLGP_RAWPATH);
            command = sb.ToString();

            sb = new StringBuilder(MAX_PATH);
            ((IShellLinkW)link).GetArguments(sb, sb.Capacity);
            args = sb.ToString();

            description = "";
            try
            {
                sb = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetDescription(sb, sb.Capacity);
                description = sb.ToString();
            }
            catch (COMException ex)
            {
            }

            sb = new StringBuilder(MAX_PATH);
            var hresult = ((IShellLinkW)link).GetIconLocation(sb, sb.Capacity, out iconIndex);

            iconLocation = sb.ToString();
            if (hresult != 0)
            {
                //CoreLib.Log("GetIconLocation result: " + hresult);
            }

            name = GetLocalizedName.GetName(filename);
        }
        // Retrieve the target path using Shell Link
        public string retrieveTargetPath(string path)
        {
            var       link      = new ShellLink();
            const int STGM_READ = 0;

            ((IPersistFile)link).Load(path, STGM_READ);
            var hwnd = new _RemotableHandle();

            ((IShellLinkW)link).Resolve(ref hwnd, 0);

            const int     MAX_PATH = 260;
            StringBuilder buffer   = new StringBuilder(MAX_PATH);

            var data = new WIN32_FIND_DATAW();

            ((IShellLinkW)link).GetPath(buffer, buffer.Capacity, ref data, SLGP_FLAGS.SLGP_SHORTPATH);
            var target = buffer.ToString();

            // To set the app description
            if (!String.IsNullOrEmpty(target))
            {
                buffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetDescription(buffer, MAX_PATH);
                description = buffer.ToString();

                StringBuilder argumentBuffer = new StringBuilder(MAX_PATH);
                ((IShellLinkW)link).GetArguments(argumentBuffer, argumentBuffer.Capacity);
                Arguments = argumentBuffer.ToString();

                // Set variable to true if the program takes in any arguments
                if (argumentBuffer.Length != 0)
                {
                    hasArguments = true;
                }
            }
            return(target);
        }
Ejemplo n.º 32
0
 static extern IntPtr FindFirstFileW([MarshalAs(UnmanagedType.LPWStr)]string lpFileName, out WIN32_FIND_DATAW lpFindFileData);
Ejemplo n.º 33
0
        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
        /// </returns>
        public bool MoveNext()
        {
            WIN32_FIND_DATAW findData = new WIN32_FIND_DATAW();

            switch (state)
            {
                case STATE_INIT:
                    state = STATE_FIND_FILES;

                    if (current != null)
                    {
                        return true;
                    }
                    else
                    {
                        goto case STATE_FIND_FILES;
                    }
                case STATE_FIND_FILES:
                    do
                    {
                        if (handle == null)
                        {
                            searchData = searchDirectories.Dequeue();

                            string searchPath = Path.Combine(searchData.path, "*");
                            handle = UnsafeNativeMethods.FindFirstFileExW(
                                searchPath,
                                infoLevel,
                                findData,
                                NativeEnums.FindExSearchOp.NameMatch,
                                IntPtr.Zero,
                                additionalFlags);

                            if (handle.IsInvalid)
                            {
                                handle.Dispose();
                                handle = null;

                                if (searchDirectories.Count > 0)
                                {
                                    continue;
                                }
                                else
                                {
                                    state = STATE_FINISH;
                                    goto case STATE_FINISH;
                                }
                            }

                            needPathDiscoveryDemand = true;
                            if (FirstFileIncluded(findData))
                            {
                                current = CreateFilePath(findData);
                                return true;
                            }
                        }

                        while (UnsafeNativeMethods.FindNextFileW(handle, findData))
                        {
                            if ((findData.dwFileAttributes & NativeConstants.FILE_ATTRIBUTE_DIRECTORY) == 0)
                            {
                                if (IsFileIncluded(findData))
                                {
                                    current = CreateFilePath(findData);
                                    return true;
                                }
                            }
                            else if (searchOption == SearchOption.AllDirectories && !findData.cFileName.Equals(".") && !findData.cFileName.Equals(".."))
                            {
                                searchDirectories.Enqueue(new SearchData(searchData, findData.cFileName));
                            }
                        }

                        handle.Dispose();
                        handle = null;

                    } while (searchDirectories.Count > 0);

                    state = STATE_FINISH;
                    goto case STATE_FINISH;
                case STATE_FINISH:
                    Dispose();
                    break;
            }

            return false;
        }
Ejemplo n.º 34
0
        public static IEnumerable<FileInfo> GetFiles(DirectoryInfo startDirectory, string pattern, bool recurse)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            Verify.IsNotNull(startDirectory, "startDirectory");
            Verify.IsNeitherNullNorEmpty(pattern, "pattern");

            // Setup
            var findData = new WIN32_FIND_DATAW();
            var directories = new Stack<DirectoryInfo>();
            directories.Push(startDirectory);

            // Process each directory.  Only push new directories if we're recursing.
            ErrorModes origErrorMode = NativeMethods.SetErrorMode(ErrorModes.FailCriticalErrors);
            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    DirectoryInfo dir = directories.Pop();
                    string dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    using (SafeFindHandle handle = NativeMethods.FindFirstFileW(dirPath + pattern, findData))
                    {
                        Win32Error error;
                        if (handle.IsInvalid)
                        {
                            error = Win32Error.GetLastError();
                            if (error == Win32Error.ERROR_ACCESS_DENIED || error == Win32Error.ERROR_FILE_NOT_FOUND)
                            {
                                continue;
                            }
                            Assert.AreNotEqual(Win32Error.ERROR_SUCCESS, error);
                            ((HRESULT)error).ThrowIfFailed();
                        }

                        do
                        {
                            if (!Utility.IsFlagSet((int)findData.dwFileAttributes, (int)FileAttributes.Directory))
                            {
                                yield return new FileInfo(dirPath + findData.cFileName);
                            }
                        }
                        while (NativeMethods.FindNextFileW(handle, findData));
                        error = Win32Error.GetLastError();
                        if (error != Win32Error.ERROR_NO_MORE_FILES)
                        {
                            ((HRESULT)error).ThrowIfFailed();
                        }
                    }

                    // Push subdirectories onto the stack if we are recursing.
                    if (recurse)
                    {
                        // In a volatile system we can't count on all the file information staying valid.
                        // Catch reasonable exceptions and move on.
                        try
                        {
                            foreach (DirectoryInfo childDir in dir.GetDirectories())
                            {
                                try
                                {
                                    FileAttributes attrib = File.GetAttributes(childDir.FullName);
                                    // If it's not a hidden, system folder, nor a reparse point
                                    if (!Utility.IsFlagSet((int)attrib, (int)(FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint)))
                                    {
                                        directories.Push(childDir);
                                    }
                                }
                                catch (FileNotFoundException)
                                {
                                    // Shouldn't see this.
                                    Assert.Fail();
                                }
                                catch (DirectoryNotFoundException) { }
                            }
                        }
                        catch (DirectoryNotFoundException) { }
                    }
                }
            }
            finally
            {
                NativeMethods.SetErrorMode(origErrorMode);
            }
        }
Ejemplo n.º 35
0
 public static extern bool FindNextFileW(IntPtr hFindFile, out WIN32_FIND_DATAW lpFindFileData);
Ejemplo n.º 36
0
        public bool ResolveShortcut(string shortcut, out string filepath, out string arguments)
        {
            ShellLink link = new ShellLink();
            ((IPersistFile)link).Load(shortcut, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            // ((IShellLinkW)link).Resolve(hwnd, 0)
            StringBuilder path = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
            ((IShellLinkW)link).GetPath(path, path.Capacity, out data, 0);

            StringBuilder args = new StringBuilder(MAX_PATH);
            ((IShellLinkW)link).GetArguments(args, args.Capacity);

            filepath = path.ToString();
            arguments = args.ToString();

            if (!File.Exists(filepath))
                return false;

            return true;
        }
Ejemplo n.º 37
0
        public static void ResolveShortcut(string filename, out string name, out string command, out string args, out string description, out string iconLocation, out int iconIndex)
        {
            ShellLink link = new ShellLink();
            ((IPersistFile)link).Load(filename, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
            //((IShellLinkW)link).Resolve(IntPtr.Zero, SLR_FLAGS.SLR_ANY_MATCH);

            StringBuilder sb = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, SLGP_FLAGS.SLGP_RAWPATH);
            command = sb.ToString();

            sb = new StringBuilder(MAX_PATH); //MAX_PATH?
            ((IShellLinkW)link).GetArguments(sb, sb.Capacity);
            args = sb.ToString();

            description = "";
            try {
                sb = new StringBuilder(MAX_PATH); //MAX_PATH?
                ((IShellLinkW)link).GetDescription(sb, sb.Capacity);
                description = sb.ToString();
            } catch (COMException ex) {
            }

            sb = new StringBuilder(MAX_PATH); //MAX_PATH?
            var hresult = ((IShellLinkW)link).GetIconLocation(sb, sb.Capacity, out iconIndex);
            iconLocation = sb.ToString();
            if (hresult != 0) {
                CoreLib.Log("GetIconLocation result: " + hresult);
            }

            name = GetLocalizedName.GetName(filename);
        }
Ejemplo n.º 38
0
 public static string ResolveShortcut(string filename)
 {
     ShellLink link = new ShellLink();
     ((IPersistFile)link).Load(filename, STGM_READ);
     // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
     // ((IShellLinkW)link).Resolve(hwnd, 0)
     StringBuilder sb = new StringBuilder(MAX_PATH);
     WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
     ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
     return sb.ToString();
 }
Ejemplo n.º 39
0
 private static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATAW lpFindFileData);
Ejemplo n.º 40
0
 private static extern IntPtr FindFirstFileW(string lpFileName, out WIN32_FIND_DATAW lpFindFileData);
Ejemplo n.º 41
0
 /// <summary>
 /// Resolves a shell shortcut's target path
 /// </summary>
 /// <param name="filename"></param>
 /// <returns></returns>
 public static string ResolveShortcut(string filename)
 {
     ShellLink link = new ShellLink();
     ((IPersistFile)link).Load(filename, STGM_READ);
     StringBuilder sb = new StringBuilder(MAX_PATH);
     WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
     ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
     return sb.ToString();
 }
Ejemplo n.º 42
0
 static extern Boolean FindNextFileW(IntPtr hFindFile, out WIN32_FIND_DATAW lpFindFileData);
Ejemplo n.º 43
0
        public static bool ResolveShortcut(out string realFilePath, string linkFilePath)
        {
            realFilePath = "<invalid>";

            try
            {
                ShellLink link = new ShellLink();
                ((IPersistFile)link).Load(linkFilePath, STGM_READ);
                StringBuilder sb = new StringBuilder(MAX_PATH);
                WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
                ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);

                realFilePath = sb.ToString();
            }
            catch(Exception)
            {
                return false;
            }

            return true;
        }
		public static extern bool FindNextFile(SafeFindHandle hFindFile, out WIN32_FIND_DATAW lpFindFileData);