2012-03-08 95 views
3
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); 
       } 

      } 
     } 
    } 
} 

我得到一個錯誤savefiledialog(): 類型或命名空間名稱「SaveFileDialog」找不到(是否缺少using指令或程序集引用?)是否有可能在Windows控制檯應用程序

我曾嘗試添加System.Windows.Forms命名空間,但我無法。

+0

你是什麼意思你不能添加System.Window.Forms命名空間?你把它添加到你的參考?你收到錯誤信息了嗎? – 2012-03-08 15:46:02

+0

我能想到做到這一點的唯一方法是爲基於Windows窗體的文件操作提供單獨的應用程序,然後從您的控制檯應用程序調用該應用程序。 – Bridge 2012-03-08 15:48:07

+0

當然,你可以做。你可能只需要在'System.Window.Forms'上添加'reference'參數 – 2012-03-08 15:50:10

回答

10

您必須添加對System.Windows.Forms部件的參考。

此外,您必須將STAThread屬性添加到您的應用程序入口點方法。

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

    Console.ReadKey(); 
} 

但說實話,這是一個可怕的想法。控制檯應用程序不應該有控制檯本身的任何其他UI。由於SaveFileDialog的名稱空間建議,SaveFileDialog只能用於Forms

+0

我做過,至少有一次,有需要這樣做,但我同意一般來說這不是一個好主意。在我的特殊情況下,我希望能夠展示一個關於對話的信息,告訴用戶需要傳遞什麼參數以及如何使用它,因爲我的用戶不會以其他方式瞭解如何爲您的控制檯應用程序。然而,重要的是,可以從命令行調用該程序,以便與其他程序(特別是PowerPoint)集成,而無需創建它自己的窗口。 – 2012-03-08 15:54:16

+0

謝謝它的作品:) – Nisha 2012-03-08 16:06:49

+0

這並不是一個壞主意。如果我想編寫一個快速程序來執行涉及文件的內容並將其交給朋友,但不希望圍繞它編寫完整的UI,則只需從控制檯應用程序中打開文件選擇器是最容易的事情。 – dtanders 2012-03-08 16:30:29

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(); 
} 

現在在你的程序開始在你的程序調用

的盡頭(之前你嘗試Console.Writeline的)調用

ConsoleHelper.AllocConsole(); 

而且

ConsoleHelper.FreeConsole(); 

現在你有一個控制檯應用程序,可以創建WinForms對話框,包括SaveFileDialog。

1

您需要將對System.Windows.Forms的引用添加到項目本身,而不是源文件。右鍵單擊解決方案資源管理器工具箱中的項目圖標,然後選擇「添加參考」。

1

您已將未導入命名空間System.Windows.Forms放入您的代碼中。

您需要添加引用System.Windows.Forms的「添加引用」對話框。然後調用命名空間'使用System.Windows.Forms'(不含引號)並使對象SaveFileDialog類。

相關問題