问题
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);
}
}
}
}
}
I am getting an error: The type or namespace name 'SaveFileDialog' could not be found (are you missing a using directive or an assembly reference?)
I did try adding the System.Windows.Forms namespace, but I was not able to.
回答1:
You have to add a reference to the System.Windows.Forms assembly.
Also, you must add the STAThread attribute to your application entry point method.
[STAThread]
private static void Main(string[] args)
{
using (SaveFileDialog sFile = new SaveFileDialog())
{
sFile.ShowDialog();
}
Console.ReadKey();
}
But honestly, that's a terrible idea. A console application shouldn't have any other UI that the console itself. As the namespace of SaveFileDialog suggests, SaveFileDialog should be used for Forms only.
回答2:
You might find it easier to reverse the problem and have a Windows Forms app with a console. To do this, create a Windows Forms app in Visual Studio. Delete the default form it creates. Open up program.cs and remove the code that tries to create a window and replace it with your console app code.
Now the trick is that you need to manually create the console. You can do it with this helper class:
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();
}
Now at the beginning of your program (before you try and Console.Writeline's) call
ConsoleHelper.AllocConsole();
And at the very end of your program call
ConsoleHelper.FreeConsole();
Now you have a console app that can create WinForms dialogs, including the SaveFileDialog.
回答3:
You need to add a reference to System.Windows.Forms to the project itself, not the source file. Right click the project icon in the Solution Explorer toolbox and select "add reference".
回答4:
You have not imported the namespace System.Windows.Forms into your code.
You need to add reference to System.Windows.Forms from 'Add Reference' Dialog Box. Then call the namespace 'using System.Windows.Forms' (without quotes) and make the object of SaveFileDialog Class.
来源:https://stackoverflow.com/questions/9620436/is-it-possible-to-have-savefiledialog-in-windows-console-applications