IRONSOFTWAREHOME
.NET幫助

C# 列印控制台:逐步指南

Jacob Mellor,首席技術官 @ Team Iron
Jacob Mellor
Updated: 2026年6月28日

向控制台列印是C#程式設計的基本方面,允許開發人員顯示資訊、與使用者互動以及除錯應用程式。 在這篇全面的文章中,我們將探討各種在C#中列印到控制台的方法,涵蓋基本輸出、格式化和進階技術。

基本控制台輸出

在C#中向控制台列印的最直接方法是使用WriteLine方法。 此方法會寫入一行文字,並在標準輸出流後面加上換行符。

using System;

class Program
{
    public static void Main()
    {
        // Output a simple greeting message to the console
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}

在此,Console.WriteLine語句將"Hello World, Welcome to C#!"輸出到控制台。 Console.WriteLine方法會自動加上換行符,導致每個後續輸出顯示在新行上。

Console.Write 用於內聯輸出

如果您想在不換行的情況下列印文字,您可以使用Write方法。 這對於單行內聯或格式化輸出很有用。

using System;

class Program
{
    public static void Main()
    {
        // Use Console.Write to print text inline without a newline
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}

在此範例中,"Hello, "和"C#!"會在同一行上列印,因為Console.WriteLine方法那樣附加換行符。

格式化輸出

C# 提供各種格式選項來控制資料在控制台應用程式中的顯示方式。 Console.WriteLine方法支持使用格式規範符的組合格式。

using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        // Using composite formatting to print variable values
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}

這裡,**{0}{1}**是age的數值佔位符。 這會導致格式化的輸出"Name: John, Age: 25"。

使用字串插值

字串插值是一種在C# 6中引入的簡潔的字串格式化方式。它允許您在字串文字中直接嵌入運算式。

using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        // Using string interpolation to format output
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}

**$符號表示字串插值,而{}**中的運算式會被求值並插入到字串中。

控制台輸出:Name: Alice, Age: 30

顯示當前日期

在這裡,我們將探討如何使用Console.WriteLine方法將當前日期列印到控制台。 這是進行除錯、記錄,或向使用者提供即時反饋的常見做法。

using System;

class Program
{
    public static void Main()
    {
        // Obtain the current date and time
        DateTime currentDate = DateTime.Now;

        // Print the current date to the console
        Console.WriteLine($"Current Date: {currentDate}");
    }
}

在此範例中,我們利用Console.WriteLine語句將此資訊列印到控制台上。 結果是清晰簡潔地顯示當前日期。

控制台輸入

除了輸出,控制台通常也用於使用者輸入。 Console.ReadLine方法允許您讀取使用者輸入的一行文字。

using System;

class Program
{
    public static void Main(string[] args)
    {
        // Prompt the user to enter their name
        Console.Write("Enter your name: ");
        
        // Read input from the user
        string variable = Console.ReadLine();
        
        // Print a personalized greeting
        Console.WriteLine($"Hello, {variable}!");
    }
}

這裡,程式提示使用者輸入他們的名稱,使用Console.ReadLine讀取輸入,然後在單行字串上列印個性化的問候語。

控制台顏色

您可以更改控制台文字的前景色和背景色以增強視覺展示。 Console.BackgroundColor屬性用於此目的。

using System;

class Program 
{
    public static void Main()
    { 
        // Set the console text color to green
        Console.ForegroundColor = ConsoleColor.Green;
        
        // Set the console background color to dark blue
        Console.BackgroundColor = ConsoleColor.DarkBlue;
        
        // Print a message with the set colors
        Console.WriteLine("Colored Console Output");
        
        // Reset colors to default
        Console.ResetColor();
    }
}

此程式碼範例將前景色設為綠色,背景色設為深藍,然後在文字列印後將顏色重置為其預設值。

進階控制台輸出

對於更進階的場景,例如列印格式化資料、表格或進度指示器,您可以探索第三方庫,例如來自NuGet包管理器的ConsoleTables或使用進階格式化技術實現自定義解決方案。

using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        // Create a new table with specified column headers
        var table = new ConsoleTable("ID", "Name", "Age");
        
        // Add rows to the table
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);
        
        // Print the table to the console
        Console.WriteLine(table);
    }
}

在此範例中,使用ConsoleTables庫將格式化表格列印到控制台。 這使得控制台窗口輸出看起來更加現代和整潔。

Console Window: Printed a formatted table to the console using "ConsoleTables" library.

IronPrint: 簡化.NET列印功能

IronPrint是由Iron Software開發的多功能列印程式庫,旨在為.NET開發人員提供強大的列印功能與應用程式的無縫整合。 無論您是在開發Web應用程式、桌面應用程式還是移動解決方案,IronPrint確保在各種.NET平台上的無縫和可部署的列印體驗。

IronPrint for .NET:C#列印程式庫

IronPrint的主要功能

1. 跨平台支持

IronPrint與多種環境相容,確保您的應用程式能跨不同平台利用其列印功能,包括:

  • Windows (7+, Server 2016+)
  • macOS (10+)
  • iOS (11+)
  • Android API 21+ (第5版"Lollipop")

2. .NET版本支持

該程式庫支持多個.NET版本,使其對於廣泛的專案非常多變:

  • .NET 8, 7, 6, 5, and Core 3.1+
  • .NET Framework (4.6.2+)

3. 專案型別支持

IronPrint符合.NET生態系中不同的專案型別:

  • 移動端 (Xamarin & MAUI & Avalonia)
  • 桌面端 (WPF & MAUI & Windows Avalonia)
  • 控制台 (應用程式 & 程式庫)

4. 廣泛的格式支持

IronPrint可以處理一系列文件格式,包括PDF, PNG, HTML, TIFF, GIF, JPEG, IMAGE, 和 BITMAP。這種靈活性使其成為處理不同型別文件的開發人員的多功能選擇。

5. 可自定的列印設定

使用IronPrint的可自定義設置量身打造您的列印經驗。 調整DPI,指定份數,設定頁面方向(縱向或橫向)及更多選項。 該程式庫賦予開發人員微調列印配置以滿足應用的需求。

安裝流程

開始使用IronPrint是一個簡單的過程。 按照以下步驟安裝該程式庫:

  1. 使用NuGet包管理器安裝IronPrint包:

    # Install IronPrint via NuGet Package Manager
    Install-Package IronPrint
    SHELL

    或者,從官方IronPrint NuGet網站或解決方案的NuGet包管理器直接下載包。

    Install IronPrint using NuGet Package Manager by searching "IronPrint" in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  2. 安裝後,在您的C#程式碼頂端包含以下語句以開始使用IronPrint:

    using IronPrint;
  3. 透過將授權金鑰值賦給License屬性來應用有效的購買許可或試用金鑰:

    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";

程式碼範例

1. 列印文件

使用IronPrint簡化列印文件。 只需將文件路徑傳遞給Print方法:

using IronPrint;

// Print the document
Printer.Print("newDoc.pdf");

2. 顯示列印對話框

要在列印前顯示列印對話框,使用ShowPrintDialog方法:

using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");

3. 自定義列印設置

透過以下程式碼實例化PrintSettings類以程式化地配置列印設置:

using IronPrint;

// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 150;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Portrait;

// Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings);

授權與支援

IronPrint是一個付費程式庫,但提供免費試用授權。 使用IronPrint的授權頁申請永久授權。 如需額外支援和諮詢,請聯繫Iron Software 團隊

結論

向控制台列印是C#開發人員必備的基本技能。 無論是基本文字輸出、格式化字串、使用者輸入,還是進階的控制台操作,了解提供的各種技術能夠讓您建立穩健且對使用者友好的控制台應用程式。 嘗試這些方法並根據您特定專案的要求進行調整。

IronPrint以強調準確性、易用性和速度而成為.NET強大的列印庫。 如需更多關於IronPrint的資訊,以及探索IronPrint所提供的全部功能和程式碼範例,請存取官方文件API參考頁面。

IronPrint還提供免費試用以在商業環境中測試其全部潛力。 然而,在試用期結束後,您需要購買授權。 其Lite包從$999開始。 從此處下載程式庫並試試看!

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費
現場演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲得非義務性諮詢
完成下列表單或發郵件到sales@ironsoftware.com
您的資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立