Home Backend Development C#.Net Tutorial How to use file IO and stream operations for data reading and writing in C# and solutions

How to use file IO and stream operations for data reading and writing in C# and solutions

Oct 08, 2023 am 08:45 AM
File io: File io operations in c#

How to use file IO and stream operations for data reading and writing in C# and solutions

How to use file IO and stream operations to read and write data and solutions in C

#During the development process, we often need to read and write files. C# provides a wealth of file IO and stream operations, making data reading and writing more flexible and efficient. This article will explore how to use file IO and stream operations to read and write data in C#, and provide specific code examples.

There are many ways to read data, common ones include reading text files, binary files, and network streams. Below we will introduce the specific implementation methods of these reading methods respectively.

  1. Reading text files

Reading text files is one of the most common ways to read data. The StreamReader class is used in C# to read text files. The code example is as follows:

1

2

3

4

5

6

7

8

9

10

string path = "文件路径";

using (StreamReader sr = new StreamReader(path))

{

    string line;

    while ((line = sr.ReadLine()) != null)

    {

        // 处理每一行的数据

        Console.WriteLine(line);

    }

}

Copy after login

In the above code, instantiate the StreamReader class and pass in the file path, and then use the ReadLine() method to read the file line by line. data in. Each row of data can be processed as needed.

  1. Reading binary files

Reading binary files requires the use of the BinaryReader class. The code example is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

string path = "二进制文件路径";

using (FileStream fs = new FileStream(path, FileMode.Open))

{

    using (BinaryReader br = new BinaryReader(fs))

    {

        byte[] buffer = new byte[1024];

        int bytesRead = 0;

 

        while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)

        {

            // 处理读取的数据

            // ...

        }

    }

}

Copy after login

In the above code, first create a FileStream Object, use the FileMode.Open parameter to open the file in read-only mode. Then create a BinaryReader object and pass in the FileStream object as a parameter. Read binary data through the Read() method and process it according to requirements.

  1. Reading the network stream

When transmitting network data, we often need to read the network stream. The TcpClient and NetworkStream classes are used in C# to read network streams. The code example is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

string serverIP = "服务器IP";

int serverPort = 8080;

 

using (TcpClient client = new TcpClient(serverIP, serverPort))

{

    using (NetworkStream ns = client.GetStream())

    {

        byte[] buffer = new byte[1024];

        int bytesRead = 0;

 

        while ((bytesRead = ns.Read(buffer, 0, buffer.Length)) > 0)

        {

            // 处理读取的网络流数据

            // ...

        }

    }

}

Copy after login

In the above code example, first create the TcpClient object and pass in the IP address and port number of the server. Then call the GetStream() method through the TcpClient object to obtain the NetworkStream object, and use the Read() method to read the network stream data.

The method of writing files is similar to that of reading. Specific code examples are given below.

  1. Write a text file

Write a text file using the StreamWriter class. The code example is as follows:

1

2

3

4

5

6

string path = "文件路径";

using (StreamWriter sw = new StreamWriter(path))

{

    string text = "要写入的文本";

    sw.WriteLine(text);

}

Copy after login

In the above code example, through the StreamWriter class Instantiate and pass in the file path, then use the WriteLine() method to write the text content to the file.

  1. Writing binary files

Writing binary files requires the use of the BinaryWriter class. The code example is as follows:

1

2

3

4

5

6

7

8

9

string path = "二进制文件路径";

using (FileStream fs = new FileStream(path, FileMode.Create))

{

    using (BinaryWriter bw = new BinaryWriter(fs))

    {

        byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };

        bw.Write(data);

    }

}

Copy after login

In the above code example, a BinaryWriter object is created , and pass in the FileStream object as a parameter. Write binary data to the file through the Write() method.

  1. Writing network stream

Writing network stream is similar to reading, using TcpClient and NetworkStream classes, the code example is as follows:

1

2

3

4

5

6

7

8

9

10

11

string serverIP = "服务器IP";

int serverPort = 8080;

 

using (TcpClient client = new TcpClient(serverIP, serverPort))

{

    using (NetworkStream ns = client.GetStream())

    {

        byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };

        ns.Write(data, 0, data.Length);

    }

}

Copy after login

The above code In the example, first create a TcpClient object and pass in the server's IP address and port number. Then call the GetStream() method through the TcpClient object to obtain the NetworkStream object, and use the Write() method to write the data to the network stream.

Summary:

This article introduces how to use C# for file IO and stream operations to read and write data. Reading of text files, binary files and network streams can be easily achieved through classes such as StreamReader, BinaryReader and NetworkStream; while classes such as StreamWriter, BinaryWriter and NetworkStream can be used to write text files, binary files and network streams. By using these classes, we can read and write data flexibly and efficiently.

The above is the detailed content of How to use file IO and stream operations for data reading and writing in C# and solutions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Testing C# .NET Applications: Unit, Integration, and End-to-End Testing Apr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

Is C# .NET Right for You? Evaluating its Applicability Is C# .NET Right for You? Evaluating its Applicability Apr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

Building Microservices with C# .NET: A Practical Guide for Architects Building Microservices with C# .NET: A Practical Guide for Architects Apr 06, 2025 am 12:08 AM

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

See all articles