跳過到頁腳內容
.NET幫助

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

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

基本控制台輸出

在 C# 中,向控制台列印內容最直接的方法是使用Console類別的WriteLine方法。 此方法將一行文字後面跟著一個換行符號寫入標準輸出流。

using System;

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

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

Friend Class Program
	Public Shared Sub Main()
		' Output a simple greeting message to the console
		Console.WriteLine("Hello World, Welcome to C#!")
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡, Console.WriteLine語句向控制台輸出"Hello World, Welcome to C#!"。 Console.WriteLine方法會自動加入換行符,使後續的每個輸出都顯示在新的一行上。

Console.Write用於內聯輸出

如果要列印文字而不換行,可以使用Console類別的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#!");
    }
}
using System;

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

Friend Class Program
	Public Shared Sub Main()
		' Use Console.Write to print text inline without a newline
		Console.Write("Hello, ")
		Console.Write("C#!")
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個例子中,"Hello, "和"C#!"印在同一行上,因為Console.Write不會像上面討論的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);
    }
}
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);
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "John"
		Dim age As Integer = 25
		' Using composite formatting to print variable values
		Console.WriteLine("Name: {0}, Age: {1}", name, age)
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡, {0}{1}分別是nameage值的佔位符。 這將產生格式化的輸出"姓名:John,年齡: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}");
    }
}
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}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		Dim name As String = "Alice"
		Dim age As Integer = 30
		' Using string interpolation to format output
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
$vbLabelText   $csharpLabel

$符號表示字串插值, {}內的表達式將被求值並插入到字串中。

控制台輸出:姓名:Alice,年齡: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}");
    }
}
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}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Obtain the current date and time
		Dim currentDate As DateTime = DateTime.Now

		' Print the current date to the console
		Console.WriteLine($"Current Date: {currentDate}")
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個範例中,我們使用DateTime.Now屬性來取得目前日期和時間。然後使用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}!");
    }
}
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}!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Prompt the user to enter their name
		Console.Write("Enter your name: ")

		' Read input from the user
		Dim variable As String = Console.ReadLine()

		' Print a personalized greeting
		Console.WriteLine($"Hello, {variable}!")
	End Sub
End Class
$vbLabelText   $csharpLabel

程式會提示使用者輸入姓名,使用Console.ReadLine讀取輸入內容,然後在一行字串中列印個人化的問候語。

控制台顏色

您可以變更控制台文字的前景色和背景色,以增強視覺效果。 Console.ForegroundColorConsole.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();
    }
}
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();
    }
}
Imports System

Friend Class Program
	Public Shared Sub 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()
	End Sub
End Class
$vbLabelText   $csharpLabel

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

高級控制台輸出

對於更進階的場景,例如列印格式化資料、表格或進度指示器,您可以探索 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);
    }
}
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);
    }
}
Imports System
Imports ConsoleTables

Friend Class Program
	Public Shared Sub Main()
		' Create a new table with specified column headers
		Dim 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)
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個例子中,我們使用ConsoleTables庫將格式化的表格列印到控制台。 這使得控制台視窗的輸出看起來更加現代、簡潔。

控制台視窗:使用ConsoleTables庫將格式化表格列印到控制台。

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+(v5"棒棒糖")

2. .NET 版本支持

該程式庫支援多種 .NET 版本,使其能夠靈活應用於各種專案:

  • 支援 .NET 8、7、6、5 和 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
    # Install IronPrint via NuGet Package Manager
    Install-Package IronPrint
    SHELL

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

    使用 NuGet 套件管理器安裝 IronPrint,方法是在 NuGet 套件管理器的搜尋欄中搜尋ironprint,然後選擇項目並點擊安裝按鈕。

  2. 安裝完成後,在 C# 程式碼頂部新增以下語句即可開始使用 IronPrint:

    using IronPrint;
    using IronPrint;
    Imports IronPrint
    $vbLabelText   $csharpLabel
  3. 透過將許可證金鑰值指派給License類別的LicenseKey屬性來應用有效的已購買授權或試用金鑰:

    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"
    $vbLabelText   $csharpLabel

程式碼範例

1. 列印文檔

使用 IronPrint 可以簡化文件列印流程。 只需將檔案路徑傳遞給Print方法即可:

using IronPrint;

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

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

' Print the document
Printer.Print("newDoc.pdf")
$vbLabelText   $csharpLabel

2. 帶對話框的列印

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

using IronPrint;

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

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

' Show print dialog
Printer.ShowPrintDialog("newDoc.pdf")
$vbLabelText   $csharpLabel

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);
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);
Imports IronPrint

' Configure print settings
Private printSettings As New PrintSettings()
printSettings.Dpi = 150
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Portrait

' Print the document with custom settings
Printer.Print("newDoc.pdf", printSettings)
$vbLabelText   $csharpLabel

許可與支持

IronPrint 雖然是付費庫,但提供免費試用許可證。 使用 IronPrint 的許可頁面申請永久許可。 如需更多支援和諮詢,請聯絡Iron Software 團隊

結論

對於 C# 開發人員來說,向控制台輸出資訊是一項基本技能。 無論是基本的文字輸出、格式化字串、使用者輸入,還是進階控制台操作,了解各種可用技術都能幫助您建立強大且使用者友好的控制台應用程式。 嘗試這些方法,並根據您特定項目的需求進行調整。

IronPrint是一款功能強大的 .NET 列印庫,以其準確性、易用性和速度而聞名。 有關 IronPrint 的更多信息,並探索 IronPrint 提供的全部功能和程式碼範例,請造訪官方文件API 參考頁面。

IronPrint 還提供免費試用,以便在商業環境中測試其全部潛力。 但是,試用期結束後,您需要購買許可證。 其 Lite 套餐起價為$799 。 從這裡下載庫文件並試用一下!

常見問題解答

C# 中列印到控制台的基本方法有哪些?

在 C# 中,列印至控制台的基本方法包括:Console.WriteLine,用於輸出帶換行的文字;Console.Write,用於輸出不帶換行的內嵌文字。

如何在 C# 中使用字串插值來進行控制台輸出?

C# 中的字串插值允許您使用 $ 符號直接在字串中包含變數,使控制台輸出的動態內容格式化更加容易。

C# 中控制台輸出有哪些進階技術?

進階技術包括使用複合格式化或類似 ConsoleTables 的函式庫來輸出結構化資料,以及使用 Console.ForegroundColorConsole.BackgroundColor 來改變文字顏色。

C# 開發人員如何從控制台讀取使用者輸入?

開發人員可以使用 Console.ReadLine 方法從控制台擷取使用者的輸入,該方法會讀取用戶輸入的一行文字。

在 C# 中更改控制台文字顏色的方法有哪些?

您可以在列印訊息到控制台之前,透過設定 Console.ForegroundColorConsole.BackgroundColor 屬性來改變控制台文字的顏色。

IronPrint 如何增强 .NET 打印功能?

IronPrint 可為各種平台和文件格式提供強大的功能,從而增強 .NET 列印功能,它還包括可自訂的列印設定,如 DPI 和紙張方向。

本印刷庫支援哪些平台和 .NET 版本?

本庫支援 Windows、macOS、iOS、Android,並與 .NET 8、7、6、5、Core 3.1+ 及 .NET Framework 4.6.2+ 相容。

如何使用 NuGet 安裝 IronPrint 函式庫?

您可以使用 NuGet 套件管理器,使用 Install-Package IronPrint 指令來安裝 IronPrint,或從 IronPrint NuGet 網站下載。

如何在 C# 中使用控制台顯示目前日期?

要在 C# 中顯示目前的日期,請使用 DateTime.Now 取得目前的日期和時間,然後再使用 Console.WriteLine 來列印。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。