跳至页脚内容
.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#!");
    }
}
$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#!");
    }
}
$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);
    }
}
$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}");
    }
}
$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}");
    }
}
$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}!");
    }
}
$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();
    }
}
$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);
    }
}
$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+(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,指定份数,设置纸张方向(纵向或横向)等等。 该库使开发人员能够微调打印配置,以满足其应用程序的需求。

要将SharpZipLib集成到你的.NET项目中:

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;
    $vbLabelText   $csharpLabel
  3. 通过将许可证密钥值分配给 @@--CODE-479--CODE-478--CODE-479 类的 @@--CODE-478--CODE-479 属性,应用有效的已购买许可证或试用密钥:

    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");
$vbLabelText   $csharpLabel

2. 带对话框的打印

要在打印前显示打印对话框,请使用ShowPrintDialog方法:

using IronPrint;

// Show print dialog
Printer.ShowPrintDialog("newDoc.pdf");
using 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);
$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 库?

您可以使用 Install-Package IronPrint 命令通过 NuGet 包管理器安装 IronPrint,或者从 IronPrint NuGet 网站下载。

如何使用 C# 的控制台显示当前日期?

要在 C# 中显示当前日期,请使用 DateTime.Now 获取当前日期和时间,然后使用 Console.WriteLine 打印出来。

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

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。

Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。

钢铁支援团队

我们每周 5 天,每天 24 小时在线。
聊天
电子邮件
打电话给我