跳至頁尾內容
.NET幫助

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

向控制台列印是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#!");
    }
}
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 用於內聯輸出

如果您想在不換行的情況下列印文字,您可以使用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.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}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}");
    }
}
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

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

控制台輸出: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}");
    }
}
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

在此範例中,我們利用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.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庫將格式化表格列印到控制台。 這使得控制台窗口輸出看起來更加現代和整潔。

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
    # 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;
    using IronPrint;
    Imports IronPrint
    $vbLabelText   $csharpLabel
  3. 透過將授權金鑰值賦給License屬性來應用有效的購買許可或試用金鑰:

    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包從$999開始。 從此處下載程式庫並試試看!

常見問題

在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套件管理器安裝IronPrint,命令為Install-Package IronPrint或從IronPrint的NuGet網站下載。

如何使用C#主控台顯示當前日期?

要在C#中顯示當前日期,使用DateTime.Now獲取當前日期和時間,然後使用Console.WriteLine列印。

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

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

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話