您真的想在控制台应用程序中显示“另存为”对话框吗?如果是这样,请查看有关问题的评论以了解如何System.Windows.Forms
从控制台应用程序引用程序集并将 using 指令添加System.Windows.Forms
到您的Program
类。我觉得有点不对劲,如果您想要一个打开对话框的应用程序,那么创建 Windows 窗体或 WPF 应用程序比创建控制台应用程序更容易。但我该评判谁?
但是,如果您想要一个控制台应用程序,并且您希望运行该应用程序的人在他们运行该应用程序时决定将输出文件保存在哪里,我会建议两种方法。
命令行参数
首先,扩展Klaus Gutter关于使用命令行参数的评论。
在方法签名中
public static void Main(string[] args)
该参数args
代表传递给您的应用程序的所有命令行参数。例如,假设您的应用程序可执行文件名为 MyApp.exe 并且您从命令行调用它:
MyApp first second "third fourth fifth" sixth
然后args
将是一个包含 4 个元素的数组,每个元素都是一个字符串,具有以下值
first
second
third fourth fifth
sixth
(请注意命令行中如何将“第三四五”括在引号中,这会导致 3 个单独的单词作为数组的单个元素而不是 3 个不同的元素传递,如果您的参数包含空格,这很有用。)
因此,对于您希望用户在运行时指定目标路径的用例,请考虑以下程序:
namespace StackOverflow68880709ConsoleAppArgs
{
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine(@"Usage: MyApp C:\Temp");
return; // or you could throw an exception here
}
var destinationFolder = args[0];
if (!Directory.Exists(destinationFolder))
{
Console.WriteLine("Destination folder " + destinationFolder + " doesn't exist");
return; // or you could throw an exception here
}
var data = "stuff to write to the file"; // put your logic to create the data here
var destinationPath = Path.Combine(destinationFolder, "MOCK_DATA_SORTED.json");
File.WriteAllText(destinationPath, data);
}
}
}
假设您的应用程序仍编译为名为 MyApp.exe 的可执行文件,您可以像这样从命令提示符运行它
MyApp C:\SomewhereIWantToSaveTheFile
或者
MyApp "C:\Some folder with spaces in the name"
接受来自控制台的输入
如果您不希望您的用户必须处理命令提示并且必须导航到 .exe 的部署位置,并且您希望他们能够通过在文件资源管理器中双击它来启动应用程序,您可以改用这种方法:
namespace StackOverflow68880709ConsoleAppArgs
{
using System;
using System.IO;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please enter destination folder");
var destinationFolder = Console.ReadLine();
if (!Directory.Exists(destinationFolder))
{
Console.WriteLine("Destination folder " + destinationFolder + " doesn't exist");
return; // or you could loop back and prompt the user again
}
var data = "stuff to write to the file"; // put your logic to create the data here
var destinationPath = Path.Combine(destinationFolder, "MOCK_DATA_SORTED.json");
File.WriteAllText(destinationPath, data);
}
}
}
此版本允许用户通过双击启动应用程序,并在控制台窗口中提示他们输入应保存输出文件的文件夹的路径。
结论
我已经向您展示了在运行时将信息传递到控制台应用程序的两种非常常见的方法,希望您会发现它们很有用。如果您是此应用程序的用户以及它的开发人员,那么您也应该能够以这两种方式中的任何一种方式运行它。
但是,如果应用程序的用户是其他一些人,他们坚持认为他们需要某种另存为对话框来浏览到目标文件夹,那么只要您从 Windows 窗体或 WPF 等 UI 框架中引入该对话框,您不妨围绕该框架构建应用程序,而不是使其成为控制台应用程序。
控制台应用程序非常适合非交互式批处理过程,并且对于技术熟练的用户社区(想想开发人员、服务器管理员等)来说效果很好,但对于习惯于做所有事情的非技术用户来说,它们就不是很好了通过单击和拖放。
欢迎来到堆栈溢出顺便说一句:-)