Is it possible to have savefiledialog () in windows console applications
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 get the error: Could not find the type or namespace name "SaveFileDialog" (are you missing a using directive or an assembly reference?)
I tried to add a namespace System.Windows.Forms
but I couldn't.
source to share
You need to add an assembly reference System.Windows.Forms
.
Also, you must add an attribute STAThread
to the entry point method in your application.
[STAThread]
private static void Main(string[] args)
{
using (SaveFileDialog sFile = new SaveFileDialog())
{
sFile.ShowDialog();
}
Console.ReadKey();
}
But honestly, this is a terrible idea . The console application should not have any other interface than the console itself. As the namespace suggests SaveFileDialog
, SaveFileDialog
should only be used for Forms
.
source to share
You might find it easier to reverse the problem and have a Windows Forms application with a console. To do this, create a Windows Forms Application in Visual Studio. Delete the default form. Open program.cs and delete the code that is trying to create the window and replace it with your console application 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 to start Console.Writeline) call
ConsoleHelper.AllocConsole();
And at the very end of your program call
ConsoleHelper.FreeConsole();
You now have a console application that can create WinForms dialogs, including SaveFileDialog.
source to share