.NET 幫助

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

查克尼思·賓
查克尼思·賓
2024年4月3日
分享:

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

基本控制台輸出

在 C# 中,最簡單的方式來列印到控制台是使用 Console 類的 WriteLine 方法。 此方法將一行文字寫入標準輸出流,並在該行後添加換行符。

using System;

class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World, Welcome to C#!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		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()
    {
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
using System;

class Program
{
    public static void Main()
    {
        Console.Write("Hello, ");
        Console.Write("C#!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		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;
        Console.WriteLine("Name: {0}, Age: {1}", name, age);
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "John";
        int age = 25;
        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
		Console.WriteLine("Name: {0}, Age: {1}", name, age)
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡,{0}{1}nameage 的佔位符。 這將生成格式化的輸出 "Name: John, Age: 25"。

使用字串插值

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

using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        string name = "Alice";
        int age = 30;
        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
		Console.WriteLine($"Name: {name}, Age: {age}")
	End Sub
End Class
$vbLabelText   $csharpLabel

$ 符號表示字串插值,並且 {} 中的表達式會被評估並插入到字串中。

控制台輸出:姓名:Alice,年齡:30

顯示當前日期

在此,我們將探討如何使用Console.WriteLine方法將當前數據打印到控制台。 這是一種常見的做法,用於除錯、記錄或向用戶提供實時反饋。

using System;

class Program
{
    public static void Main()
    {
        // Assuming you have some date to display, let's say the current date
        DateTime currentDate = DateTime.Now;

        // Using Console.WriteLine to print the current date to the console
        // before/after some action which needs debugging to analyze the problem
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
using System;

class Program
{
    public static void Main()
    {
        // Assuming you have some date to display, let's say the current date
        DateTime currentDate = DateTime.Now;

        // Using Console.WriteLine to print the current date to the console
        // before/after some action which needs debugging to analyze the problem
        Console.WriteLine($"Current Date: {currentDate}");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main()
		' Assuming you have some date to display, let's say the current date
		Dim currentDate As DateTime = DateTime.Now

		' Using Console.WriteLine to print the current date to the console
		' before/after some action which needs debugging to analyze the problem
		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 [])
    {
        Console.Write("Enter your name: ");
        string variable = Console.ReadLine();
        Console.WriteLine($"Hello, {variable}!");
    }
}
using System;

class Program
{
    public static void Main(string args [])
    {
        Console.Write("Enter your name: ");
        string variable = Console.ReadLine();
        Console.WriteLine($"Hello, {variable}!");
    }
}
Imports System

Friend Class Program
	Public Shared Sub Main(String ByVal () As args)
		Console.Write("Enter your name: ")
		Dim variable As String = Console.ReadLine()
		Console.WriteLine($"Hello, {variable}!")
	End Sub
End Class
$vbLabelText   $csharpLabel

這裡,程式會提示使用者輸入他們的名字,使用 Console.ReadLine 來讀取輸入,然後在一條字串行中打印個人化的問候訊息。

控制台顏色

您可以更改控制台文本的前景色和背景色,以增強視覺效果。 Console.ForegroundColorConsole.BackgroundColor 屬性用於此目的。

using System;

class Program 
{
public static void Main()
    { 
        Console.ForegroundColor = ConsoleColor.Green;
        Console.BackgroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine("Colored Console Output");
        // Reset colors to default
        Console.ResetColor();
    }
}
using System;

class Program 
{
public static void Main()
    { 
        Console.ForegroundColor = ConsoleColor.Green;
        Console.BackgroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine("Colored Console Output");
        // Reset colors to default
        Console.ResetColor();
    }
}
Imports System

Friend Class Program
Public Shared Sub Main()
		Console.ForegroundColor = ConsoleColor.Green
		Console.BackgroundColor = ConsoleColor.DarkBlue
		Console.WriteLine("Colored Console Output")
		' Reset colors to default
		Console.ResetColor()
End Sub
End Class
$vbLabelText   $csharpLabel

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

進階主控台輸出

對於更高級的場景,如打印格式化數據、表格或進度指示器,您可以探索使用 NuGet Package Manager 的 ConsoleTables 等第三方庫,或者使用高級格式化技術實現自定義解決方案。

using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        var table = new ConsoleTable("ID", "Name", "Age");
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);
        Console.WriteLine(table);
    }
}
using System;
using ConsoleTables;

class Program
{
    public static void Main()
    { 
        var table = new ConsoleTable("ID", "Name", "Age");
        table.AddRow(1, "John", 25);
        table.AddRow(2, "Alice", 30);
        Console.WriteLine(table);
    }
}
Imports System
Imports ConsoleTables

Friend Class Program
	Public Shared Sub Main()
		Dim table = New ConsoleTable("ID", "Name", "Age")
		table.AddRow(1, "John", 25)
		table.AddRow(2, "Alice", 30)
		Console.WriteLine(table)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此範例中,使用ConsoleTables程式庫將格式化的表格列印到控制台上。 這使控制台窗口的輸出具有現代且更清晰的外觀。

控制台窗口:使用 ConsoleTables 庫將格式化的表格打印到控制台。

IronPrint:簡化 .NET 列印功能

IronPrint 是由 Iron Software 開發的多功能打印庫,旨在使 .NET 開發人員能夠將強大的打印功能無縫整合到其應用程式中。 無論您正在開發網頁應用程式、桌面應用程式或行動解決方案,IronPrint 確保在各種 .NET 平台上提供無縫且可部署的列印體驗。

IronPrint for .NET:C# 列印庫

IronPrint的主要功能

跨平台支持

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

  • Windows (7+, Server 2016+)
  • macOS (10+)
  • iOS (11+)
  • Android API 21+(版本5“Lollipop”)

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 套件:
    :ProductInstall

或者,直接從官方的IronPrint NuGet網站或從方案的NuGet封裝管理員下載套件。

使用 NuGet 套件管理器安裝 IronPrint,請在 NuGet 套件管理器的搜索欄中搜尋「ironprint」,然後選擇專案並點擊安裝按鈕。

  1. 安裝後,請在您的 C# 代碼開頭包含以下語句來開始使用 IronPrint:
    using IronPrint;
    using IronPrint;
Imports IronPrint
$vbLabelText   $csharpLabel
  1. 通過將許可證密鑰值指定給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 setting
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 setting
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 setting
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 套餐起始於 $749。 從這裡下載該庫並嘗試使用!

查克尼思·賓
軟體工程師
Chaknith 致力於 IronXL 和 IronBarcode。他在 C# 和 .NET 方面擁有豐富的專業知識,協助改進軟體並支持客戶。他從用戶互動中獲得的洞察力有助於提高產品、文檔和整體體驗。
< 上一頁
C# 列印清單:快速教程
下一個 >
C# 列印語句:學習基礎知識

準備開始了嗎? 版本: 2025.4 剛剛發布

查看許可證 >