获取命令行参数
通过 Environment
类获取
// 在App.xaml.cs的启动方法中使用 protected override void OnStartup(StartupEventArgs e) { // 方法1:直接使用e.Args(推荐) string[] args = e.Args; // 方法2:Environment.GetCommandLineArgs() string[] allArgs = Environment.GetCommandLineArgs(); // 注意:allArgs[0]是程序路径,实际参数从索引1开始 if (args.Length > 0) { string filePath = args[0]; MainWindow window = new MainWindow(filePath); window.Show(); } else { new MainWindow().Show(); } }
修改 App.xaml
配置
<Application x:Class="YourApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml" Startup="App_Startup"> <!-- 手动指定启动事件 --> </Application>
传递参数的3种方式
Visual Studio 调试设置
- 项目属性 → 调试 → 打开
launchSettings.json
- 添加参数:
"profiles": { "YourApp": { "commandLineArgs": "\"C:\\test.txt\" -mode=admin" } }
命令行启动
YourApp.exe "D:\data\file.docx" -theme=dark
快捷方式传递
- 创建快捷方式 → 右键属性
- 在”目标”末尾添加参数:
"C:\AppPath\YourApp.exe" "config.json"
参数解析进阶技巧
封装解析类
public class CommandLineArgs { public string FilePath { get; set; } public bool IsAdminMode { get; set; } public static CommandLineArgs Parse(string[] args) { var result = new CommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].StartsWith("-") || args[i].StartsWith("/")) { switch (args[i].Substring(1).ToLower()) { case "admin": result.IsAdminMode = true; break; } } else if (File.Exists(args[i])) { result.FilePath = args[i]; } } return result; } }
使用第三方库
推荐库:CommandLineParser
(NuGet包)
// 定义参数模型 class Options { [Option('f', "file", Required = true)] public string File { get; set; } [Option('m', "mode")] public string Mode { get; set; } } // 在启动时解析 Parser.Default.ParseArguments<Options>(args) .WithParsed(options => { // 使用options.File和options.Mode });
实际应用场景
- 文件关联启动
Windows注册文件类型后,双击文档自动传递路径参数 - 权限控制
YourApp.exe -user=admin
启动管理员模式 - 主题切换
YourApp.exe -theme=dark
应用深色主题 - 调试模式
YourApp.exe -debug
启用日志输出
注意事项
- 参数安全性
验证输入路径:if(!File.Exists(args[0])) throw new FileNotFoundException();
- 空格处理
用双引号包裹含空格的路径:"C:\My Documents\file.txt"
- 跨平台差异
Linux/macOS中参数区分大小写(Windows不区分) - 编码问题
非英文字符建议使用UTF-8:Console.InputEncoding = Encoding.UTF8;
最佳实践:
- 关键参数提供默认值(如
--mode=normal
)- 使用
--help
参数输出使用说明- 敏感数据(如密码)避免通过命令行传递
引用说明参考微软官方文档:
WPF Application Startup Processing
Environment.GetCommandLineArgs()
CommandLineParser Library
通过命令行参数,您可以使WPF应用更灵活地适应不同场景,提升用户体验和操作效率,建议在正式环境中对参数进行严格验证,确保应用安全稳定运行。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/8772.html