.NET ヘルプ

C# コンソールに出力する(開発者向けの使い方)

更新済み 4月 3, 2024
共有:

コンソールへの印刷は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 メソッドを使用します。 これは、インラインまたは1行としてフォーマットされた出力に便利です。

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#

この例では、1行目に「こんにちは」、2行目に「C# (シーシャープ)」と記述しています。!コンソール.Writeは改行文字を追加しないので、2行目の "は同じ行に出力される。 これが、前述の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#

記号は文字列の補間を表し、 $ 内の式は文字列の補間を表す。{}** が評価され、文字列に挿入される。

コンソールの出力名前アリス, 年齢: 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 を使って入力を読み、そしてパーソナライズされた挨拶メッセージを1行の文字列に表示します。

コンソールの色

コンソールテキストの前景色と背景色を変更して、視覚的な表現を強化することができます。 この目的のために、Console.ForegroundColorプロパティとConsole.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 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
VB   C#

この例では、ConsoleTables ライブラリを使用して、フォーマットされた表をコンソールに表示している。 これにより、コンソールのウィンドウ出力はモダンですっきりとした印象になる。

コンソール・ウィンドウ:ConsoleTables ライブラリを使って、コンソールにフォーマットされた表を表示。

IronPrint (アイアンプリント):.NET 印刷機能の合理化

IronPrint は、.NET開発者がアプリケーションに堅牢な印刷機能をシームレスに統合できるように設計された、アイアンソフトウェア(Iiron Software)によって開発された多目的印刷ライブラリです。 Webアプリケーション、デスクトップアプリケーション、モバイルソリューションのいずれを開発している場合でも、IronPrintは様々な.NETプラットフォームでシームレスかつデプロイ可能なプリント体験を保証します。

.NET 用アイアンプリント:C#(シーシャープ)印刷ライブラリ

IronPrintの主な機能

1.クロスプラットフォーム対応

IronPrintは様々な環境と互換性があり、お客様のアプリケーションは以下のような様々なプラットフォームで印刷機能を活用することができます:

  • ウィンドウズ (7以上、サーバー2016以上)
  • マックオス (10+)
  • iOS (11+)
  • Android API 21以上 (v5 "ロリポップ")

2. .NET バージョンサポート

このライブラリーは複数の.NETバージョンをサポートしているため、幅広いプロジェクトに対応できる:

  • .NET 8、7、6、5、およびコア3.1以上
  • .NETフレームワーク (4.6.2+)

3.プロジェクト・タイプ

IronPrint (アイアンプリント)は.NETエコシステム内の様々なプロジェクトタイプに対応しています:

  • モバイル (Xamarin & MAUI & アバロニア)
  • デスクトップ (WPF & MAUI & Windows Avalonia)

  • コンソール (アプリ&ライブラリー)

4.幅広いフォーマットをサポート

IronPrintはPDF、PNG、HTML、TIFF、GIF、JPEG、IMAGE、BITMAPを含む様々なドキュメントフォーマットを扱うことができます。この柔軟性により、さまざまな種類のドキュメントを扱う開発者にとって多用途な選択肢となります。

5.カスタマイズ可能な印刷設定

IronPrint のカスタマイズ可能な設定で、印刷体験をカスタマイズしましょう。 Dpiの調整、コピー部数の指定、用紙の向きの設定 (ポートレートまたはランドスケープ)など。 このライブラリにより、開発者はアプリケーションのニーズに合わせて印刷設定を微調整することができる。

インストール手順

アイアンプリントを始めるのは簡単です。 以下の手順に従って、ライブラリをインストールしてください:

  1. NuGetパッケージマネージャを使用してIronPrintパッケージをインストールします:
    :ProductInstall

または、公式の アイアンプリントNuGetウェブサイト またはNuGet Package Manager for Solutionsから。

![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.ダイアログ付き印刷

印刷前に印刷ダイアログを表示するには 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")
VB   C#

3.印刷設定のカスタマイズ

をインスタンス化することで、プログラムで印刷設定を行います。 プリント設定 クラスは次のコードを使っている:

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(アイアンプリント)を使って永久ライセンスを申し込む。 ライセンスページ. その他のサポートやお問い合わせは、下記までご連絡ください。 アイアンソフトウェアチーム.

結論

コンソールへの印刷は、C#(シーシャープ)開発者にとって基本的なスキルです。 基本的なテキスト出力、フォーマットされた文字列、ユーザー入力、高度なコンソール操作など、様々なテクニックを理解することで、堅牢でユーザーフレンドリーなコンソールアプリケーションを作成することができます。 これらの方法を試し、特定のプロジェクトの要件に合うように適応させる。

IronPrint .NET用の強力な印刷ライブラリとして、正確さ、使いやすさ、スピードに重点を置いています。 IronPrint (アイアンプリント)に関する詳細情報、およびIronPrintが提供する全機能とコード例については、公式サイトをご覧ください。 ドキュメント 以下のコンテンツを日本語に翻訳してください: APIリファレンス ページ

IronPrint も提供しています。 無料トライアル 商業環境でその潜在能力をフルに試すためだ。 を購入する必要がある。 ライセンス 試用期間終了後 Liteパッケージは $599 から始まる。 ライブラリを以下からダウンロード これ 試してみてください。!

< 以前
C#でリストを印刷する(開発者向けの方法)
次へ >
デベロッパー向けC#のプリント文(その仕組み)

準備はできましたか? バージョン: 2024.8 新発売

無料のNuGetダウンロード 総ダウンロード数: 7,144 View Licenses >