Exemple #1
0
        private static string GetSpecialFolder(WshShell ws, SpecialFolders specialFolder)
        {
            object o      = specialFolder.ToString();
            string folder = ws.SpecialFolders.Item(ref o) as string;

            return(folder);
        }
        public static SpecialFolders GetSpecialFolders(DirectoryInfo di)
        {
            var sf = new SpecialFolders();

            foreach (var sfd in EnumSpecialFolders(di))
            {
                var sfType = sfd.info.type;
                sfType = sfType != null?sfType.ToLower() : null;

                switch (sfType)
                {
                case "dlls":
                    sf.dlls.Add(sfd);
                    break;

                case "locales":
                    sf.locales.Add(sfd);
                    break;

                case "plugins":
                    sf.plugins.Add(sfd);
                    break;

                default:
                    sf.others.Add(sfd);
                    break;
                }
            }
            return(sf);
        }
Exemple #3
0
        private static string GetShortcutPath(WshShell ws, SpecialFolders specialFolder, string name)
        {
            string folder = GetSpecialFolder(ws, specialFolder);
            string path   = Path.Combine(folder, name + ".lnk");

            return(path);
        }
Exemple #4
0
 public override bool Execute()
 {
     foreach (var game in model.GameData)
     {
         if (!game.Value.SaveDir.StartsWith("??"))
         {
             Model.InstalledVersion latest = null;
             FileInfo latestFile           = null;
             foreach (var version in model.Settings.InstalledVersions)
             {
                 DirectoryInfo src = new DirectoryInfo(SpecialFolders.CurrentUserSaveDirCemu(version, game.Value));
                 FileInfo      fi  = GetNewestFile(src);
                 if (fi != null)
                 {
                     if (latestFile == null || latestFile.LastWriteTime < fi.LastWriteTime)
                     {
                         latestFile = fi;
                         latest     = version;
                     }
                 }
             }
             if (latest != null)
             {
                 CopySaveFolder(game.Value, latest);
             }
         }
     }
     return(true);
 }
Exemple #5
0
        private void GetBackup(HttpServer.IHttpRequest request, HttpServer.IHttpResponse response, HttpServer.Sessions.IHttpSession session, BodyWriter bw)
        {
            HttpServer.HttpInput input = request.Method.ToUpper() == "POST" ? request.Form : request.QueryString;
            var bk = Program.DataConnection.GetBackup(input["id"].Value);

            if (bk == null)
            {
                ReportError(response, bw, "Invalid or missing backup id");
            }
            else
            {
                var scheduleId  = Program.DataConnection.GetScheduleIDsFromTags(new string[] { "ID=" + bk.ID });
                var schedule    = scheduleId.Any() ? Program.DataConnection.GetSchedule(scheduleId.First()) : null;
                var sourcenames = SpecialFolders.GetSourceNames(bk);

                //TODO: Filter out the password in both settings and the target url

                bw.OutputOK(new
                {
                    success = true,
                    data    = new {
                        Schedule     = schedule,
                        Backup       = bk,
                        DisplayNames = sourcenames
                    }
                });
            }
        }
Exemple #6
0
        public static String GetFolderPath(SpecialFolders aFolder)
        {
            StringBuilder builder = new StringBuilder(256);

            SHGetFolderPath(0, (int)aFolder, 0, 0, builder);
            return(builder.ToString());
        }
 public static void DeleteShortcut(SpecialFolders specialFolder, string name)
 {
     WshShell ws = new WshShellClass();
     string path = GetShortcutPath(ws, specialFolder, name);
     if (System.IO.File.Exists(path))
     {
         System.IO.File.Delete(path);
     }
 }
Exemple #8
0
        public static void DeleteShortcut(SpecialFolders specialFolder, string name)
        {
            WshShell ws   = new WshShellClass();
            string   path = GetShortcutPath(ws, specialFolder, name);

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
        }
 public ICollection <FileSystemEntryInfo> GetSpecialFolders()
 {
     return(SpecialFolders
            .Select(aSpecialFolder =>
                    new FileSystemEntryInfo(
                        aSpecialFolder,
                        Path.Combine(UserProfilePath, aSpecialFolder),
                        GlobalData.FolderIcon))
            .OrderBy(aSpecialFolder => aSpecialFolder.Name)
            .ToArray());
 }
Exemple #10
0
        public static string GetPath(this SpecialFolders specialFolder)
        {
            Guid?folderGuid = GetGuid(specialFolder);

            if (folderGuid.HasValue)
            {
                NativeMethods.Shell32.SHGetKnownFolderPath(folderGuid.Value, 0, IntPtr.Zero, out string path);
                return(path);
            }
            return(null);
        }
        public static string SpecialFolder(SpecialFolders folder)
        {
            var path = Environment.GetFolderPath((Environment.SpecialFolder)folder);

            // https://github.com/nuke-build/nuke/pull/825#discussion_r848954724
            if (path.IsNullOrEmpty() && folder == SpecialFolders.UserProfile)
            {
                path = Environment.GetEnvironmentVariable("USERPROFILE");
            }

            return(path);
        }
Exemple #12
0
        internal Serializable.ImportExportStructure PrepareBackupForExport(IBackup backup)
        {
            var scheduleId = GetScheduleIDsFromTags(new string[] { "ID=" + backup.ID });

            return(new Serializable.ImportExportStructure()
            {
                CreatedByVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                Backup = (Database.Backup)backup,
                Schedule = (Database.Schedule)(scheduleId.Any() ? GetSchedule(scheduleId.First()) : null),
                DisplayNames = SpecialFolders.GetSourceNames(backup)
            });
        }
 public static void CreateShortcut(SpecialFolders specialFolder, string name, string exePath)
 {
     WshShell ws = new WshShellClass();
     string path = GetShortcutPath(ws, specialFolder, name);
     WshShortcut shortcut = ws.CreateShortcut(path) as WshShortcut;
     shortcut.TargetPath = exePath;
     shortcut.WindowStyle = 1;
     //shortcut.Hotkey = "CTRL+SHIFT+F";
     shortcut.IconLocation = exePath + ", 0";
     shortcut.Description = name;
     shortcut.WorkingDirectory = Path.GetDirectoryName(exePath);
     shortcut.Save();
 }
Exemple #14
0
        public static void CreateShortcut(SpecialFolders specialFolder, string name, string exePath)
        {
            WshShell    ws       = new WshShellClass();
            string      path     = GetShortcutPath(ws, specialFolder, name);
            WshShortcut shortcut = ws.CreateShortcut(path) as WshShortcut;

            shortcut.TargetPath  = exePath;
            shortcut.WindowStyle = 1;
            //shortcut.Hotkey = "CTRL+SHIFT+F";
            shortcut.IconLocation     = exePath + ", 0";
            shortcut.Description      = name;
            shortcut.WorkingDirectory = Path.GetDirectoryName(exePath);
            shortcut.Save();
        }
        private void ZipImport()
        {
            InstalledVersion version = model.Settings.InstalledVersions.FirstOrDefault(v => v.IsLatest);

            // Configure open file dialog box
            if (version != null)
            {
                string pluginFileName = Path.Combine(SpecialFolders.PlugInFolder(model), plugIn.FileName);

                if (!File.Exists(pluginFileName))
                {
                    using (OpenFileDialog dlg = new OpenFileDialog())
                    {
                        dlg.Filter = plugIn.FileName + Resources.FormExecutePlugIn_ZipImport____ + plugIn.FileName + Resources.FormExecutePlugIn_ZipImport__;

                        // Show open file dialog box
                        if (dlg.ShowDialog() == DialogResult.OK)
                        {
                            if (File.Exists(dlg.FileName))
                            {
                                File.Copy(dlg.FileName, Path.Combine(SpecialFolders.PlugInFolder(model), plugIn.FileName));
                            }
                        }
                    }
                }

                if (File.Exists(pluginFileName))
                {
                    ZipArchive zipArchive = ZipFile.OpenRead(pluginFileName);
                    foreach (var file in plugIn.Files)
                    {
                        if (File.Exists(Path.Combine(version.Folder, file.DestinationFolder, file.Name)))
                        {
                            if (!File.Exists(Path.Combine(version.Folder, file.DestinationFolder, "_" + file.Name)))
                            {
                                File.Move(Path.Combine(version.Folder, file.DestinationFolder, file.Name), Path.Combine(version.Folder, file.DestinationFolder, "_" + file.Name));
                            }
                        }
                        foreach (ZipArchiveEntry zippedFile in zipArchive.Entries)
                        {
                            if (zippedFile.FullName.Contains(file.SourceFolder + "/" + file.Name))
                            {
                                Unpacker.ExtractFile(zippedFile, Path.Combine(version.Folder, file.DestinationFolder, file.Name));
                            }
                        }
                    }
                }
            }
        }
 public AndroidSpecialFolders()
 {
     SpecialFolders.Add("Data", Environment.DataDirectory.CanonicalPath);
     SpecialFolders.Add("Alarms", Environment.DirectoryAlarms);
     SpecialFolders.Add("Dcim", Environment.DirectoryDcim);
     SpecialFolders.Add("Documents", Environment.DirectoryDocuments);
     SpecialFolders.Add("Downloads", Environment.DirectoryDownloads);
     SpecialFolders.Add("Movies", Environment.DirectoryMovies);
     SpecialFolders.Add("Music", Environment.DirectoryMusic);
     SpecialFolders.Add("Notifications", Environment.DirectoryNotifications);
     SpecialFolders.Add("Pictures", Environment.DirectoryPictures);
     SpecialFolders.Add("Podcasts", Environment.DirectoryPodcasts);
     SpecialFolders.Add("Ringtones", Environment.DirectoryRingtones);
     SpecialFolders.Add("DownloadCache", Environment.DownloadCacheDirectory.CanonicalPath);
     SpecialFolders.Add("ExternalStorage", Environment.ExternalStorageDirectory.CanonicalPath);
     SpecialFolders.Add("Root", Environment.RootDirectory.CanonicalPath);
 }
Exemple #17
0
        private void CopySaveFolder(Model.GameInformation game, Model.InstalledVersion latest)
        {
            DirectoryInfo src    = new DirectoryInfo(SpecialFolders.CurrentUserSaveDirCemu(latest, game));
            DirectoryInfo src255 = new DirectoryInfo(SpecialFolders.CommonUserFolderCemu(latest, game));

            DirectoryInfo dest    = new DirectoryInfo(SpecialFolders.CurrentUserSaveDirBudford(model, model.CurrentUser, game, ""));
            DirectoryInfo dest255 = new DirectoryInfo(SpecialFolders.CommonSaveDirBudford(model, game, ""));

            if (Directory.Exists(src.FullName))
            {
                if (src.GetFiles().Any() || src.GetDirectories().Any() || (Directory.Exists(src255.FullName) && (src255.GetFiles().Any() || src255.GetDirectories().Any())))
                {
                    Launcher.UpdateFolder(src, dest, true);
                    Launcher.UpdateFolder(src255, dest255, true);
                }
            }
        }
Exemple #18
0
        public static string SpecialFolder(SpecialFolders folder)
        {
#if NETCORE
            if (Platform == PlatformFamily.Windows)
            {
                return(Windows.GetFolder(folder));
            }
            if (IsUnix)
            {
                return(Unix.GetFolder(folder));
            }

            throw new NotSupportedException($"Not supported for platform '{Platform}'.");
#else
            return(Environment.GetFolderPath(s_lookup[folder]));
#endif
        }
        private static Instance GetFromVs2017Instance(
            MSBuildVersion version,
            MSBuildPlatform platform,
            VisualStudioEdition edition,
            SpecialFolders specialFolder)
        {
            var versionDirectoryName = version.ToString().TrimStart("VS");
            var basePath             = Path.Combine(
                EnvironmentInfo.SpecialFolder(specialFolder).NotNull(),
                $@"Microsoft Visual Studio\{versionDirectoryName}\{edition}\MSBuild\{GetVersionFolder(version)}\Bin");

            return(new Instance(
                       version,
                       platform,
                       platform == MSBuildPlatform.x64
                    ? Path.Combine(basePath, "amd64")
                    : basePath));
        }
Exemple #20
0
        /// <summary>
        /// Получить путь к реальному (live) файлу-конфигу.
        /// </summary>
        /// <param name="currentConfigPath">Путь к оригинальному файлу-конфигу.</param>
        /// <param name="forceReturnAppDataPath">Принудительно возвращать путь к appdata.</param>
        /// <returns>Путь к реальному (live) файлу-конфигу.</returns>
        private static string GetLiveConfigFilePath(string currentConfigPath, bool forceReturnAppDataPath)
        {
            var nameWithoutExt = Path.GetFileNameWithoutExtension(currentConfigPath);
            var liveConfigName = nameWithoutExt + ".live" + Path.GetExtension(currentConfigPath);

            if (!forceReturnAppDataPath)
            {
                var liveConfigBesideCurrent = Path.Combine(Path.GetDirectoryName(currentConfigPath), liveConfigName);
                if (!IsFileLocked(liveConfigBesideCurrent))
                {
                    return(liveConfigBesideCurrent);
                }
            }
            var appDataPath = Path.Combine(SpecialFolders.ProductUserApplicationData("Configs",
                                                                                     Path.GetDirectoryName(currentConfigPath).GetMD5Hash().Substring(0, 8)), liveConfigName);

            return(appDataPath);
        }
Exemple #21
0
        public ToolsViewModel(Config config, ProgressViewModel progressView, OperationLocker locker, Window mainWindow, SpecialFolders specialFolders, Logger logger, PatchingManager patchingManager, AndroidDebugBridge debugBridge, QuestPatcherUIService uiService, InfoDumper dumper)
        {
            Config       = config;
            ProgressView = progressView;
            Locker       = locker;

            _mainWindow      = mainWindow;
            _specialFolders  = specialFolders;
            _logger          = logger;
            _patchingManager = patchingManager;
            _debugBridge     = debugBridge;
            _uiService       = uiService;
            _dumper          = dumper;

            _debugBridge.StoppedLogging += (_, _) =>
            {
                _logger.Information("ADB log exited");
                _isAdbLogging = false;
                this.RaisePropertyChanged(nameof(AdbButtonText));
            };
        }
Exemple #22
0
            public static string GetFolder(SpecialFolders folder)
            {
                if (!s_lookup.ContainsKey(folder))
                {
                    return(null);
                }

                var builder = new StringBuilder(capacity: 260);
                var result  = SHGetFolderPath(IntPtr.Zero, s_lookup[folder], IntPtr.Zero, dwFlags: 0, lpszPath: builder);

                if (result < 0)
                {
                    if (result == unchecked ((int)0x80131539))
                    {
                        throw new PlatformNotSupportedException();
                    }
                    return(null);
                }

                return(builder.ToString());
            }
Exemple #23
0
            // ReSharper disable once CyclomaticComplexity
            public static string GetFolder(SpecialFolders folder)
            {
                switch (folder)
                {
                case SpecialFolders.System:
                    return("/bin");

                case SpecialFolders.ProgramFiles:
                case SpecialFolders.ProgramFilesX86:
                    return("/user/bin");

                case SpecialFolders.UserProfile:
                case SpecialFolders.LocalApplicationData:
                case SpecialFolders.ApplicationData:
                    var value = getenv("HOME");
                    if (value == IntPtr.Zero)
                    {
                        return(null);
                    }

                    var size = 0;
                    while (Marshal.ReadByte(value, size) != 0)
                    {
                        size++;
                    }

                    if (size != 0)
                    {
                        return(string.Empty);
                    }

                    var buffer = new byte[size];
                    Marshal.Copy(value, buffer, startIndex: 0, length: size);
                    return(Encoding.UTF8.GetString(buffer));

                default:
                    return(null);
                }
            }
Exemple #24
0
        private Dictionary <string, string> GetSourceNames(Duplicati.Server.Serialization.Interface.IBackup backup)
        {
            var systemIO = Duplicati.Library.Snapshots.SnapshotUtility.SystemIO;

            return(backup.Sources.Distinct().Select(x => {
                var sp = SpecialFolders.TranslateToDisplayString(x);
                if (sp != null)
                {
                    return new KeyValuePair <string, string>(x, sp);
                }

                x = SpecialFolders.ExpandEnvironmentVariables(x);
                try {
                    var nx = x;
                    if (nx.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                    {
                        nx = nx.Substring(0, nx.Length - 1);
                    }
                    var n = systemIO.PathGetFileName(nx);
                    if (!string.IsNullOrWhiteSpace(n))
                    {
                        return new KeyValuePair <string, string>(x, n);
                    }
                } catch {
                }

                if (x.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) && x.Length > 1)
                {
                    return new KeyValuePair <string, string>(x, x.Substring(0, x.Length - 1).Substring(x.Substring(0, x.Length - 1).LastIndexOf("/") + 1));
                }
                else
                {
                    return new KeyValuePair <string, string>(x, x);
                }
            }).ToDictionary(x => x.Key, x => x.Value));
        }
 public static string SpecialFolder(SpecialFolders folder)
 {
     return(Environment.GetFolderPath((Environment.SpecialFolder)folder));
 }
 private static string GetSpecialFolder(WshShell ws, SpecialFolders specialFolder)
 {
     object o = specialFolder.ToString();
     string folder = ws.SpecialFolders.Item(ref o) as string;
     return folder;
 }
Exemple #27
0
        public void GET(string key, RequestInfo info)
        {
            var parts = (key ?? "").Split(new char[] { '/' }, 2);
            var bk    = Program.DataConnection.GetBackup(parts.First());

            if (bk == null)
            {
                info.ReportClientError("Invalid or missing backup id", System.Net.HttpStatusCode.NotFound);
            }
            else
            {
                if (parts.Length > 1)
                {
                    var operation = parts.Last().Split(new char[] { '/' }).First().ToLowerInvariant();

                    switch (operation)
                    {
                    case "files":
                        var filter = parts.Last().Split(new char[] { '/' }, 2).Skip(1).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(info.Request.QueryString["filter"].Value))
                        {
                            filter = info.Request.QueryString["filter"].Value;
                        }
                        SearchFiles(bk, filter, info);
                        return;

                    case "log":
                        FetchLogData(bk, info);
                        return;

                    case "remotelog":
                        FetchRemoteLogData(bk, info);
                        return;

                    case "filesets":
                        ListFileSets(bk, info);
                        return;

                    case "export":
                        Export(bk, info);
                        return;

                    case "isdbusedelsewhere":
                        IsDBUsedElseWhere(bk, info);
                        return;

                    case "isactive":
                        IsActive(bk, info);
                        return;

                    default:
                        info.ReportClientError(string.Format("Invalid component: {0}", operation));
                        return;
                    }
                }

                var scheduleId  = Program.DataConnection.GetScheduleIDsFromTags(new string[] { "ID=" + bk.ID });
                var schedule    = scheduleId.Any() ? Program.DataConnection.GetSchedule(scheduleId.First()) : null;
                var sourcenames = SpecialFolders.GetSourceNames(bk);

                //TODO: Filter out the password in both settings and the target url

                info.OutputOK(new GetResponse()
                {
                    success = true,
                    data    = new GetResponse.GetResponseData()
                    {
                        Schedule     = schedule,
                        Backup       = bk,
                        DisplayNames = sourcenames
                    }
                });
            }
        }
 /// <summary>
 /// Get the special folder.
 /// </summary>
 /// <param name="folder">The special folder name.</param>
 /// <returns>The special folder path.</returns>
 public string GetSpecialFolders(SpecialFolders folder)
 {
     return(_specialFolders[(int)folder]);
 }
Exemple #29
0
        private void Process(string command, string path, RequestInfo info)
        {
            if (string.IsNullOrEmpty(path))
            {
                info.ReportClientError("No path parameter was found");
                return;
            }

            bool skipFiles  = Library.Utility.Utility.ParseBool(info.Request.QueryString["onlyfolders"].Value, false);
            bool showHidden = Library.Utility.Utility.ParseBool(info.Request.QueryString["showhidden"].Value, false);

            string specialpath  = null;
            string specialtoken = null;

            if (path.StartsWith("%"))
            {
                var ix = path.IndexOf("%", 1);
                if (ix > 0)
                {
                    var tk   = path.Substring(0, ix + 1);
                    var node = SpecialFolders.Nodes.Where(x => x.id.Equals(tk, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                    if (node != null)
                    {
                        specialpath  = node.resolvedpath;
                        specialtoken = node.id;
                    }
                }
            }

            path = SpecialFolders.ExpandEnvironmentVariables(path);

            if (Duplicati.Library.Utility.Utility.IsClientLinux && !path.StartsWith("/"))
            {
                info.ReportClientError("The path parameter must start with a forward-slash");
                return;
            }

            if (!string.IsNullOrWhiteSpace(command))
            {
                if ("validate".Equals(command, StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        if (System.IO.Path.IsPathRooted(path) && (System.IO.Directory.Exists(path) || System.IO.File.Exists(path)))
                        {
                            info.OutputOK();
                            return;
                        }
                    }
                    catch
                    {
                    }

                    info.ReportServerError("File or folder not found");
                    return;
                }
                else
                {
                    info.ReportClientError(string.Format("No such operation found: {0}", command));
                    return;
                }
            }

            try
            {
                if (path != "" && path != "/")
                {
                    path = Duplicati.Library.Utility.Utility.AppendDirSeparator(path);
                }

                IEnumerable <Serializable.TreeNode> res;

                if (!Library.Utility.Utility.IsClientLinux && (path.Equals("/") || path.Equals("")))
                {
                    res =
                        from di in System.IO.DriveInfo.GetDrives()
                        where di.DriveType == DriveType.Fixed || di.DriveType == DriveType.Network || di.DriveType == DriveType.Removable
                        select new Serializable.TreeNode()
                    {
                        id   = di.RootDirectory.FullName,
                        text =
                            (
                                string.IsNullOrWhiteSpace(di.VolumeLabel) ?
                                di.RootDirectory.FullName.Replace('\\', ' ') :
                                di.VolumeLabel + " - " + di.RootDirectory.FullName.Replace('\\', ' ')
                            ) + "(" + di.DriveType + ")",
                        iconCls = "x-tree-icon-drive"
                    };
                }
                else
                {
                    res = ListFolderAsNodes(path, skipFiles, showHidden);
                }

                if ((path.Equals("/") || path.Equals("")) && specialtoken == null)
                {
                    // Prepend special folders
                    res = SpecialFolders.Nodes.Union(res);
                }

                if (specialtoken != null)
                {
                    res = res.Select(x => {
                        x.resolvedpath = x.id;
                        x.id           = specialtoken + x.id.Substring(specialpath.Length);
                        return(x);
                    });
                }

                info.OutputOK(res);
            }
            catch (Exception ex)
            {
                info.ReportClientError("Failed to process the path: " + ex.Message);
            }
        }
Exemple #30
0
        /// <summary>
        /// Selects a path from a value from the SpecialFolders enumeration.
        /// </summary>
        /// <param name="specialFolder">The SpecialFolder to select</param>
        /// <returns>The TreeNode of the directory which was selected, this will be null if the directory
        /// doesn't exist</returns>
        public TreeNode SelectPath(SpecialFolders specialFolder, bool expandNode)
        {
            StringBuilder path = new StringBuilder(256);
            IntPtr pidl = IntPtr.Zero;

            if (specialFolder == SpecialFolders.Desktop)
                return SelectPath("Desktop", expandNode);
            else if (ShellAPI.SHGetFolderPath(
                    IntPtr.Zero, (ShellAPI.CSIDL)specialFolder,
                    IntPtr.Zero, ShellAPI.SHGFP.TYPE_CURRENT, path) == ShellAPI.S_OK)
            {
                path.Replace(ShellBrowser.MyDocumentsPath, ShellBrowser.MyDocumentsName);
                return SelectPath(path.ToString(), expandNode);
            }
            else
            {
                #region Get Pidl

                if (specialFolder == SpecialFolders.MyDocuments)
                {
                    uint pchEaten = 0;
                    ShellAPI.SFGAO pdwAttributes = 0;
                    ShellBrowser.DesktopItem.ShellFolder.ParseDisplayName(
                        IntPtr.Zero,
                        IntPtr.Zero,
                        "::{450d8fba-ad25-11d0-98a8-0800361b1103}",
                        ref pchEaten,
                        out pidl,
                        ref pdwAttributes);
                }
                else
                {
                    ShellAPI.SHGetSpecialFolderLocation(
                        IntPtr.Zero,
                        (ShellAPI.CSIDL)specialFolder,
                        out pidl);
                }

                #endregion

                #region Make Path

                if (pidl != IntPtr.Zero)
                {
                    IntPtr strr = Marshal.AllocCoTaskMem(ShellAPI.MAX_PATH * 2 + 4);
                    Marshal.WriteInt32(strr, 0, 0);
                    StringBuilder buf = new StringBuilder(ShellAPI.MAX_PATH);

                    if (ShellBrowser.DesktopItem.ShellFolder.GetDisplayNameOf(
                                    pidl,
                                    ShellAPI.SHGNO.FORADDRESSBAR | ShellAPI.SHGNO.FORPARSING,
                                    strr) == ShellAPI.S_OK)
                    {
                        ShellAPI.StrRetToBuf(strr, pidl, buf, ShellAPI.MAX_PATH);
                    }

                    Marshal.FreeCoTaskMem(pidl);
                    Marshal.FreeCoTaskMem(strr);

                    if (!string.IsNullOrEmpty(buf.ToString()))
                        return SelectPath(buf.ToString(), expandNode);
                    else
                        return null;
                }
                else
                    return null;

                #endregion
            }
        }
 private void ConfigFullPathShouldNotContainsAppdata()
 {
     this.liveConfigPath.Contains(SpecialFolders.ProductUserApplicationData("Configs")).Should().BeFalse();
 }
 private static string GetShortcutPath(WshShell ws, SpecialFolders specialFolder, string name)
 {
     string folder = GetSpecialFolder(ws, specialFolder);
     string path = Path.Combine(folder, name + ".lnk");
     return path;
 }
		public static SpecialFolders GetSpecialFolders(DirectoryInfo di) {
			var sf = new SpecialFolders();
			foreach(var sfd in EnumSpecialFolders(di)){
				var sfType = sfd.info.type;
				sfType = sfType != null ? sfType.ToLower() : null;
				switch (sfType) {
					case "dlls":
						sf.dlls.Add(sfd);
						break;
					case "locales":
						sf.locales.Add(sfd);
						break;
					case "plugins":
						sf.plugins.Add(sfd);
						break;
					default:
						sf.others.Add(sfd);
						break;
				}
			}
			return sf;
		}
Exemple #34
0
 public static String GetFolderPath(SpecialFolders aFolder)
 {
     StringBuilder builder = new StringBuilder(256);
       SHGetFolderPath(0, (int) aFolder, 0, 0, builder);
       return builder.ToString();
 }
        /// <summary>
        /// Selects a path from a value from the SpecialFolders enumeration.
        /// </summary>
        /// <param name="specialFolder">The SpecialFolder to select</param>
        /// <returns>The TreeNode of the directory which was selected, this will be null if the directory
        /// doesn't exist</returns>
        public TreeNode SelectPath(SpecialFolders specialFolder, bool expandNode)
        {
            StringBuilder path = new StringBuilder(256);
            IntPtr        pidl = IntPtr.Zero;

            if (specialFolder == SpecialFolders.Desktop)
            {
                return(SelectPath("Desktop", expandNode));
            }
            else if (ShellAPI.SHGetFolderPath(
                         IntPtr.Zero, (ShellAPI.CSIDL)specialFolder,
                         IntPtr.Zero, ShellAPI.SHGFP.TYPE_CURRENT, path) == ShellAPI.S_OK)
            {
                path.Replace(ShellBrowser.MyDocumentsPath, ShellBrowser.MyDocumentsName);
                return(SelectPath(path.ToString(), expandNode));
            }
            else
            {
                #region Get Pidl

                if (specialFolder == SpecialFolders.MyDocuments)
                {
                    uint           pchEaten      = 0;
                    ShellAPI.SFGAO pdwAttributes = 0;
                    ShellBrowser.DesktopItem.ShellFolder.ParseDisplayName(
                        IntPtr.Zero,
                        IntPtr.Zero,
                        "::{450d8fba-ad25-11d0-98a8-0800361b1103}",
                        ref pchEaten,
                        out pidl,
                        ref pdwAttributes);
                }
                else
                {
                    ShellAPI.SHGetSpecialFolderLocation(
                        IntPtr.Zero,
                        (ShellAPI.CSIDL)specialFolder,
                        out pidl);
                }

                #endregion

                #region Make Path

                if (pidl != IntPtr.Zero)
                {
                    IntPtr strr = Marshal.AllocCoTaskMem(ShellAPI.MAX_PATH * 2 + 4);
                    Marshal.WriteInt32(strr, 0, 0);
                    StringBuilder buf = new StringBuilder(ShellAPI.MAX_PATH);

                    if (ShellBrowser.DesktopItem.ShellFolder.GetDisplayNameOf(
                            pidl,
                            ShellAPI.SHGNO.FORADDRESSBAR | ShellAPI.SHGNO.FORPARSING,
                            strr) == ShellAPI.S_OK)
                    {
                        ShellAPI.StrRetToBuf(strr, pidl, buf, ShellAPI.MAX_PATH);
                    }

                    Marshal.FreeCoTaskMem(pidl);
                    Marshal.FreeCoTaskMem(strr);

                    if (!string.IsNullOrEmpty(buf.ToString()))
                    {
                        return(SelectPath(buf.ToString(), expandNode));
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }

                #endregion
            }
        }
Exemple #36
0
        private void Process(string command, string path, RequestInfo info)
        {
            if (string.IsNullOrEmpty(path))
            {
                info.ReportClientError("No path parameter was found");
                return;
            }

            bool skipFiles  = Library.Utility.Utility.ParseBool(info.Request.QueryString["onlyfolders"].Value, false);
            bool showHidden = Library.Utility.Utility.ParseBool(info.Request.QueryString["showhidden"].Value, false);

            string specialpath  = null;
            string specialtoken = null;

            if (path.StartsWith("%"))
            {
                var ix = path.IndexOf("%", 1);
                if (ix > 0)
                {
                    var tk   = path.Substring(0, ix + 1);
                    var node = SpecialFolders.Nodes.Where(x => x.id.Equals(tk, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (node != null)
                    {
                        specialpath  = node.resolvedpath;
                        specialtoken = node.id;
                    }
                }
            }

            path = SpecialFolders.ExpandEnvironmentVariables(path);

            if (Duplicati.Library.Utility.Utility.IsClientLinux && !path.StartsWith("/"))
            {
                info.ReportClientError("The path parameter must start with a forward-slash");
                return;
            }

            if (!string.IsNullOrWhiteSpace(command))
            {
                if ("validate".Equals(command, StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        if (System.IO.Path.IsPathRooted(path) && (System.IO.Directory.Exists(path) || System.IO.File.Exists(path)))
                        {
                            info.OutputOK();
                            return;
                        }
                    }
                    catch
                    {
                    }

                    info.ReportServerError("File or folder not found");
                    return;
                }
                else
                {
                    info.ReportClientError(string.Format("No such operation found: {0}", command));
                    return;
                }
            }

            try
            {
                if (path != "" && path != "/")
                {
                    path = Duplicati.Library.Utility.Utility.AppendDirSeparator(path);
                }

                IEnumerable <Serializable.TreeNode> res;

                if (!Library.Utility.Utility.IsClientLinux && (path.Equals("/") || path.Equals("")))
                {
                    res = DriveInfo.GetDrives()
                          .Where(di =>
                                 (di.DriveType == DriveType.Fixed || di.DriveType == DriveType.Network || di.DriveType == DriveType.Removable) &&
                                 di.IsReady                  // Only try to create TreeNode entries for drives who were ready 'now'
                                 )
                          .Select(TryCreateTreeNodeForDrive) // This will try to create a TreeNode for selected drives
                          .Where(tn => tn != null);          // This filters out such entries that could not be created
                }
                else
                {
                    res = ListFolderAsNodes(path, skipFiles, showHidden);
                }

                if ((path.Equals("/") || path.Equals("")) && specialtoken == null)
                {
                    // Prepend special folders
                    res = SpecialFolders.Nodes.Union(res);
                }

                if (specialtoken != null)
                {
                    res = res.Select(x => {
                        x.resolvedpath = x.id;
                        x.id           = specialtoken + x.id.Substring(specialpath.Length);
                        return(x);
                    });
                }

                // We have to resolve the query before giving it to OutputOK
                // If we do not do this, and the query throws an exception when OutputOK resolves it,
                // the exception would not be handled properly
                res = res.ToList();

                info.OutputOK(res);
            }
            catch (Exception ex)
            {
                info.ReportClientError("Failed to process the path: " + ex.Message);
            }
        }
Exemple #37
0
 private static Guid?GetGuid(this SpecialFolders specialFolder) => Guids.ContainsKey(specialFolder) ? (Guid?)Guids[specialFolder] : null;