.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
VB   C#

這裡,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
VB   C#

在這個例子中,"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
VB   C#

這裡,{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
VB   C#

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

控制台输出:名稱: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
VB   C#

在此範例中,我們使用 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
VB   C#

在這裡,程序提示用戶輸入他們的名字,使用 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
VB   C#

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

進階主控台輸出

對於更高級的情境,例如列印格式化數據、表格或進度指標,您可以探索來自 NuGet 套件管理器的第三方庫,例如 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
VB   C#

在此範例中,使用 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+(v5 "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」,然後選擇專案並點擊安裝按鈕。](/static-assets/print/blog/csharp-print-cole/csharp-print-cole-4.webp)
  1. 安裝後,請在您的 C# 代碼開頭包含以下語句來開始使用 IronPrint:
    using IronPrint;
    using IronPrint;
Imports IronPrint
VB   C#
  1. 將有效的購買授權或試用金鑰指派給 License 類別的 LicenseKey 屬性:
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
    License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01";
License.LicenseKey = "IRONPRINT.MYLICENSE.KEY.1EF01"
VB   C#

程式碼範例

1. 列印文件

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

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")
VB   C#

2. 使用對話框列印

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

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")
VB   C#

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)
VB   C#

授權與支援

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

結論

在控制台列印是 C# 開發人員的一項基本技能。 無論是基本的文字輸出、格式化字串、使用者輸入,還是進階的控制檯操作,了解各種可用的技術能使您創建穩健且使用者友好的控制檯應用程式。 請嘗試這些方法,並根據您特定項目的要求進行調整。

IronPrint作為一個功能強大的 .NET 列印庫,其突出表現在於準確性、易用性和速度。 如需更多關於 IronPrint 的資訊以及探索 IronPrint 提供的完整功能和代碼範例,請造訪官方網站。文檔API 參考文獻頁面。

IronPrint 也提供一個免費試用在商業環境中測試其全部潛力。 不過,您需要購買一個許可證試用期結束後。 其 Lite 套餐從 $749 起。 從下載該庫這裡並試一試!

< 上一頁
C# 列印清單:快速教程
下一個 >
C# 列印語句:學習基礎知識