|
| 1 | +// WorkingDirectoryHelper.cs |
| 2 | +// Fix for Issue #39305: Peek's "open with" leaves working directory in PowerToys |
| 3 | +// Ensures launched applications get the correct working directory |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Diagnostics; |
| 7 | +using System.IO; |
| 8 | + |
| 9 | +namespace Peek.Common.Helpers |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Helper for launching external applications with correct working directory. |
| 13 | + /// </summary> |
| 14 | + public static class WorkingDirectoryHelper |
| 15 | + { |
| 16 | + /// <summary> |
| 17 | + /// Launches an application with the working directory set to the file's location. |
| 18 | + /// </summary> |
| 19 | + /// <param name="filePath">The file to open.</param> |
| 20 | + /// <param name="applicationPath">Optional specific application to use.</param> |
| 21 | + public static void OpenWithCorrectWorkingDirectory(string filePath, string? applicationPath = null) |
| 22 | + { |
| 23 | + if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) |
| 24 | + { |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + var directory = Path.GetDirectoryName(filePath); |
| 29 | + |
| 30 | + var startInfo = new ProcessStartInfo |
| 31 | + { |
| 32 | + FileName = applicationPath ?? filePath, |
| 33 | + WorkingDirectory = directory ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), |
| 34 | + UseShellExecute = true, |
| 35 | + }; |
| 36 | + |
| 37 | + if (!string.IsNullOrEmpty(applicationPath)) |
| 38 | + { |
| 39 | + startInfo.Arguments = $"\"{filePath}\""; |
| 40 | + } |
| 41 | + |
| 42 | + try |
| 43 | + { |
| 44 | + Process.Start(startInfo); |
| 45 | + } |
| 46 | + catch (Exception ex) |
| 47 | + { |
| 48 | + // Log error but don't throw - graceful degradation |
| 49 | + System.Diagnostics.Debug.WriteLine($"Failed to open file: {ex.Message}"); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + /// <summary> |
| 54 | + /// Opens the "Open with" dialog with correct working directory. |
| 55 | + /// </summary> |
| 56 | + public static void ShowOpenWithDialog(string filePath) |
| 57 | + { |
| 58 | + if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath)) |
| 59 | + { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + var directory = Path.GetDirectoryName(filePath); |
| 64 | + |
| 65 | + var startInfo = new ProcessStartInfo |
| 66 | + { |
| 67 | + FileName = "rundll32.exe", |
| 68 | + Arguments = $"shell32.dll,OpenAs_RunDLL \"{filePath}\"", |
| 69 | + WorkingDirectory = directory ?? string.Empty, |
| 70 | + UseShellExecute = false, |
| 71 | + }; |
| 72 | + |
| 73 | + try |
| 74 | + { |
| 75 | + Process.Start(startInfo); |
| 76 | + } |
| 77 | + catch |
| 78 | + { |
| 79 | + // Fallback to default behavior |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments