是否可以在Windows控制台应用程序中使用savefiledialog()

Nis*_*sha 3 c# console-application winforms

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Diagnostics
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = null;
            using (SaveFileDialog sFile = new SaveFileDialog())
            {
                sFile.Filter = "Text (Tab delimited)(*.txt)|*.txt|CSV (Comma separated)(*.csv)|*.csv";
                if (sFile.ShowDialog() == DialogResult.OK)
                {
                    filename = sFile.FileName;
                    WriteRegKey(diagnostic, filename);
                }

            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:无法找到类型或命名空间名称'SaveFileDialog'(您是否缺少using指令或程序集引用?)

我确实尝试添加System.Windows.Forms命名空间,但我无法.

Mat*_*and 11

您可能会发现更容易扭转问题并使用带有控制台的Windows窗体应用程序.为此,请在Visual Studio中创建Windows窗体应用程序.删除它创建的默认表单.打开program.cs并删除尝试创建窗口的代码并将其替换为您的控制台应用程序代码.

现在的诀窍是你需要手动创建控制台.您可以使用此帮助程序类执行此操作:

public class ConsoleHelper
{
    /// <summary>
    /// Allocates a new console for current process.
    /// </summary>
    [DllImport("kernel32.dll")]
    public static extern Boolean AllocConsole();

    /// <summary>
    /// Frees the console.
    /// </summary>
    [DllImport("kernel32.dll")]
    public static extern Boolean FreeConsole();
}
Run Code Online (Sandbox Code Playgroud)

现在在你的程序开始时(在你尝试和Console.Writeline之前)调用

ConsoleHelper.AllocConsole(); 
Run Code Online (Sandbox Code Playgroud)

并在你的程序调用结束时

ConsoleHelper.FreeConsole();
Run Code Online (Sandbox Code Playgroud)

现在您有一个可以创建WinForms对话框的控制台应用程序,包括SaveFileDialog.


ken*_*n2k 10

您必须添加对System.Windows.Forms程序集的引用.

此外,您必须将该STAThread属性添加到应用程序入口点方法.

[STAThread]
private static void Main(string[] args)
{
    using (SaveFileDialog sFile = new SaveFileDialog())
    {
        sFile.ShowDialog();
    }

    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

但老实说,这是一个糟糕的主意.控制台应用程序不应具有控制台本身的任何其他UI.作为SaveFileDialog建议的命名空间,SaveFileDialog应该只用于Forms.