目次
Examples of File Handling in C#
Example #5

C# でのファイル処理

Sep 03, 2024 pm 03:23 PM
c# c# tutorial

The operations of file creation, reading the contents from the file, writing the contents to the file, file appending, etc., is referred to as file handling. When the file is opened for reading and writing, it is called a stream, which is a byte sequence used for communication; the stream is of two types input stream to read the file, output stream to write the file, these two streams are handled by system.IO namespace in C#. It consists of file structure and directory structure information. There are classes in the system.IO namespace to support file handling in c#. The list of classes is:

  • Binary Reader: This class is used to read primitive data from the binary stream.
  • Binary Writer: This class is used to write primitive data into the binary stream.
  • File stream: Data is read and written from the file using this class.

Examples of File Handling in C#

Following are the examples of file handling in C#:

Example #1

C# program to demonstrate binary reader, binary writer, file stream classes to create a file, read the contents from the file and write contents into the file.

using System;
using System.IO;
public class BinStream
{
public BinStream()
{
Writerfunc();
Readerfunc();
}
public static void Main()
{
BinStream bs1 = new BinStream();
Console.ReadLine();
}
private void Writerfunc()
{
try
{
Console.Out.WriteLine("Let's get started ...");
//a FileStream is opened on the file "new"
FileStream fout1 = new FileStream("new.txt", FileMode.OpenOrCreate,
FileAccess.Write, FileShare.ReadWrite);
//a BinaryWriter is created from the FileStream
BinaryWriter bw1 = new BinaryWriter(fout1);
//arbitrary variables are created
string name1 = "Shobha";
int age1 = 28;
double height1 = 5.5;
bool single1 = true;
char gender1 = 'F';
//values are written to the file
bw1.Write(name1);
bw1.Write(age1);
bw1.Write(height1);
bw1.Write(single1);
bw1.Write(gender1);
//file and free resources are closed
bw1.Close();
Console.WriteLine("Data updated!");
Console.WriteLine();
}
catch (IOException e)
{
Console.WriteLine("occurance of an input output exception :" + e);
}
}
private void Readerfunc()
{
try
{
Console.WriteLine("Lets get started to Read ...");
//FileStream is opened in Read mode
FileStream fin1 = new FileStream("new.txt", FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
//a BinaryReader is created from the FileStream
BinaryReader br1 = new BinaryReader(fin1);
//start of the file is searched
br1.BaseStream.Seek(0, SeekOrigin.Begin);
//the file is read and the values are stored to the variables
string name1 = br1.ReadString();
int age1 = br1.ReadInt32();
double height1 = br1.ReadDouble();
bool single1 = br1.ReadBoolean();
char gender1 = br1.ReadChar();
//the data is displayed on the console
Console.WriteLine("Your Name :" + name1);
Console.WriteLine("Your Age :" + age1);
Console.WriteLine("Your Height :" + height1);
Console.WriteLine("Are you Single? :" + single1);
Console.WriteLine("Your Gender M/F:" + gender1);
<em> </em>//stream is closed and the resources are freed
br1.Close();
Console.WriteLine("Read the data successfully!");
}
catch (IOException e)
{
Console.WriteLine("occurance of an input output exception :" + e);
}
}
}

The output of the above code is shown below:

C# でのファイル処理

  • Buffered Stream: This class provides temporary storage for a stream of bytes.
  • Memory stream: The streamed data stored in the memory can be randomly accessed using this class

Example #2

C# program to demonstrate the use of buffered stream class and memory stream class

using System;
using System.Diagnostics;
using System.IO;
public class Program
{
public void Main()
{
var check = Stopwatch.StartNew();
// buffer writes to a MemoryStream by using buffered stream.
using (MemoryStream memory = new MemoryStream())
using (BufferedStream stream = new BufferedStream(memory))
{
// a byte is written 5 million times.
for (int i = 0; i < 5000000; i++)
{
stream.WriteByte(5);
}
}
check.Stop();
Console.WriteLine("BUFFEREDSTREAM TIME: " + check.Elapsed.TotalMilliseconds);
}
}

The output of the above code is shown in the snapshot below:

C# でのファイル処理

  • Directory: This class manipulated the structure of the directory.
  • Directory info: Operations are performed on the directories using this class.

Example #3

C# program to demonstrate the use of directory class and directory info class

using System;
using System.IO;
namespace CSharp
{
class Programcheck
{
static void Main(string[] args)
{
//directory name is provided along with complete location.   DirectoryInfo directory = new DirectoryInfo(@"C:\\Users\\shivakumarsh\\Desktop\\dir1");
try
{
// A check is done to see if directory exists or no
if (directory.Exists)
{
Console.WriteLine("A directory by this name already exists");
return;
}
// a new directory is created.
directory.Create();
Console.WriteLine("New directory is created");
}
catch (Exception e)
{
Console.WriteLine("Directory cannot be created: {0}", e.ToString());
}
}
}
}

The output of the above code is shown in the snapshot below:

C# でのファイル処理

  • Drive info: Drives are provided with information using this class.

Example #4

C# program to demonstrate the use of drive info class

using System;
using System.IO;
class Programcheck
{
static void Main()
{
//the drive names are printed.
var drives1 = DriveInfo.GetDrives();
foreach (DriveInfo info in drives1)
{
Console.WriteLine(info.Name);
}
}
}

The output of the above program is shown in the snapshot below:

C# でのファイル処理

  • File: Files are manipulated using this class
  • File info: Operations are performed on the files using this class.
  • Path: Operations are performed on the path information using this class.
  • Stream Reader: Characters are read from the byte stream using this class.
  • Stream writer: Characters are written into the byte stream using this class.

Example #5

C# program to demonstrate the use of the file, file info, path, stream reader, stream writer class

using System;
using System.IO;
class programcheck
{
public static void Main()
{
string path1 = Path.GetTempFileName();
var file1 = new FileInfo(path1);
//A file is created to write into it
using (StreamWriter swe = file1.CreateText())
{
swe.WriteLine("Welcome");
swe.WriteLine("to");
swe.WriteLine("C#");
}
// A file is opened to read from it
using (StreamReader sre = file.OpenText())
{
var sh = "";
while ((sh = sre.ReadLine()) != null)
{
Console.WriteLine(sh);
}
}
try
{
string path22 = Path.GetTempFileName();
var file2 = new FileInfo(path22);
// making sure there is no target
file2.Delete();
// File is copied.
file1.CopyTo(path22);
Console.WriteLine($"{path1} was copied to {path22}.");
// newly created file is deleted.
file2.Delete();
Console.WriteLine($"{path2} was deleted.");
}
catch (Exception e)
{
Console.WriteLine($" failed process: {e.ToString()}");
}
}
}

The output of the above code is shown in the snapshot below:

C# でのファイル処理

  • String Reader: Reading can be done from the string buffer using this class.
  • String Writer: Writing can be done into the string buffer using this class.

Example #5

C# program to demonstrate the use of string reader and string writer class

using System;
using System.IO;
namespace CSharp
{
public class check
{
public static void Main(string[] args)
{
StringWriter strn = new StringWriter();
strn.WriteLine("Welcome to C#");
strn.Close();
// Creating an instance of StringReader and StringWriter is passed
StringReader read = new StringReader(strn.ToString());
// data is being read
while (read.Peek() > -1)
{
Console.WriteLine(read.ReadLine());
}
}
}
}

The output of the above code is shown in the snapshot below:

C# でのファイル処理

以上がC# でのファイル処理の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

C#対C:歴史、進化、将来の見通し C#対C:歴史、進化、将来の見通し Apr 19, 2025 am 12:07 AM

C#とCの歴史と進化はユニークであり、将来の見通しも異なります。 1.Cは、1983年にBjarnestrostrupによって発明され、オブジェクト指向のプログラミングをC言語に導入しました。その進化プロセスには、C 11の自動キーワードとラムダ式の導入など、複数の標準化が含まれます。C20概念とコルーチンの導入、将来のパフォーマンスとシステムレベルのプログラミングに焦点を当てます。 2.C#は2000年にMicrosoftによってリリースされました。CとJavaの利点を組み合わせて、その進化はシンプルさと生産性に焦点を当てています。たとえば、C#2.0はジェネリックを導入し、C#5.0は非同期プログラミングを導入しました。これは、将来の開発者の生産性とクラウドコンピューティングに焦点を当てます。

C#.NET:.NETエコシステムを使用したアプリケーションの構築 C#.NET:.NETエコシステムを使用したアプリケーションの構築 Apr 27, 2025 am 12:12 AM

.NETを使用してアプリケーションを構築する方法は? .NETを使用してアプリケーションを構築することは、次の手順を通じて達成できます。1)C#言語やクロスプラットフォーム開発サポートを含む.NETの基本を理解します。 2)コンポーネントや.NETエコシステムの作業原則などのコア概念を学習します。 3)単純なコンソールアプリケーションから複雑なWebAPISおよびデータベース操作まで、基本的および高度な使用をマスターします。 4)構成やデータベース接続の問題など、一般的なエラーとデバッグ手法に精通している。 5)アプリケーションのパフォーマンスの最適化と非同期プログラミングやキャッシュなどのベストプラクティス。

Webからデスクトップまで:C#.NETの汎用性 Webからデスクトップまで:C#.NETの汎用性 Apr 15, 2025 am 12:07 AM

c#.netisversatileforbothwebanddesktopdevelopment.1)forweb、useasp.netfordynamicapplications.2)fordesktop、equindowsorwpfforrichinterfaces.3)usexamarinforcross-platformdeveliment、enabling deshacrosswindows、

.NETフレームワーク対C#:用語のデコード .NETフレームワーク対C#:用語のデコード Apr 21, 2025 am 12:05 AM

.NetFrameworkはソフトウェアフレームワークであり、C#はプログラミング言語です。 1..netframeworkは、デスクトップ、Web、モバイルアプリケーションの開発をサポートするライブラリとサービスを提供します。 2.C#は.NetFrameWork用に設計されており、最新のプログラミング機能をサポートしています。 3..NetFrameworkはCLRを介してコード実行を管理し、C#コードはILにコンパイルされ、CLRによって実行されます。 4. .NetFrameWorkを使用してアプリケーションをすばやく開発し、C#はLINQなどの高度な関数を提供します。 5.一般的なエラーには、タイプ変換と非同期プログラミングデッドロックが含まれます。 VisualStudioツールは、デバッグに必要です。

azure/awsへのc#.netアプリケーションの展開:ステップバイステップガイド azure/awsへのc#.netアプリケーションの展開:ステップバイステップガイド Apr 23, 2025 am 12:06 AM

c#.netアプリをAzureまたはAWSに展開する方法は?答えは、AzureAppServiceとAwselasticBeanStalkを使用することです。 1。Azureでは、AzureAppServiceとAzurePipelinesを使用して展開を自動化します。 2。AWSでは、Amazon ElasticBeanstalkとAwslambdaを使用して、展開とサーバーレス計算を実装します。

C#.NET:コアの概念とプログラミングの基礎を探る C#.NET:コアの概念とプログラミングの基礎を探る Apr 10, 2025 am 09:32 AM

C#は、Microsoftによって開発された最新のオブジェクト指向プログラミング言語であり、.NETフレームワークの一部として開発されています。 1.C#は、カプセル化、継承、多型を含むオブジェクト指向プログラミング(OOP)をサポートしています。 2。C#の非同期プログラミングは非同期を通じて実装され、適用応答性を向上させるためにキーワードを待ちます。 3. LINQを使用してデータ収集を簡潔に処理します。 4.一般的なエラーには、null参照の例外と、範囲外の例外インデックスが含まれます。デバッグスキルには、デバッガーと例外処理の使用が含まれます。 5.パフォーマンスの最適化には、StringBuilderの使用と、不必要な梱包とボクシングの回避が含まれます。

ユニティゲーム開発:C#は3D物理エンジンとAIの動作ツリーを実装しています ユニティゲーム開発:C#は3D物理エンジンとAIの動作ツリーを実装しています May 16, 2025 pm 02:09 PM

Unityでは、3D物理エンジンとAIの動作ツリーをC#を通じて実装できます。 1. rigidbodyコンポーネントとaddforceメソッドを使用して、スクロールボールを作成します。 2。動作を通じて、パトロールやChaseplayerなどのツリーノードを介して、AIキャラクターはプレーヤーをパトロールして追いかけるように設計できます。

汎用性のある.NET言語としてのC#:アプリケーションと例 汎用性のある.NET言語としてのC#:アプリケーションと例 Apr 26, 2025 am 12:26 AM

C#は、エンタープライズレベルのアプリケーション、ゲーム開発、モバイルアプリケーション、Web開発で広く使用されています。 1)エンタープライズレベルのアプリケーションでは、C#がasp.netcoreにWebAPIを開発するためによく使用されます。 2)ゲーム開発では、C#がUnityエンジンと組み合わされて、ロールコントロールやその他の機能を実現します。 3)C#は、コードの柔軟性とアプリケーションのパフォーマンスを改善するために、多型と非同期プログラミングをサポートします。

See all articles