.NET 帮助

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

查克尼特·宾
查克尼特·宾
2024年四月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 的占位符。 这样的格式化输出结果是 "姓名:John,年龄:25":约翰,年龄: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包管理器的第三方库,例如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 的主要功能

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 软件包:
    :ProductInstall

或者,直接从官方IronPrint NuGet网站或解决方案的NuGet包管理器下载该包。

在 NuGet 包管理器中搜索“ironprint”以安装 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 刚刚发布

查看许可证 >