search
HomeBackend DevelopmentC#.Net TutorialHow to use file IO and stream operations to read and write data in C#

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

Oct 08, 2023 am 11:10 AM
c# file io operationc# stream operationsData reading and writing technology

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

How to use file IO and stream operations to read and write data in C# requires specific code examples

In C# programming, file IO and stream operations are commonly used technologies , used to read and write data from files. Whether processing text files, binary files, or reading network stream data, we can do it through file IO and stream operations.

File IO and stream operations provide a flexible way to process data, and can read or write any type of data, making it easier for us to process files and data streams in our programs.

The following will introduce in detail how to use C# for file IO and stream operations, and give some specific code examples.

1. File IO operations

File IO operations in C# can be implemented using the classes provided by the System.IO namespace. The following are some commonly used file IO operation methods:

  1. Create a file:
string filePath = "D:\test.txt";

using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
    // 执行文件操作
}
  1. Read a text file:
string filePath = "D:\test.txt";

using (StreamReader streamReader = new StreamReader(filePath))
{
    string content = streamReader.ReadToEnd();
    Console.WriteLine(content);
}
  1. Write text file:
string filePath = "D:\test.txt";
string content = "Hello, World!";

using (StreamWriter streamWriter = new StreamWriter(filePath))
{
    streamWriter.Write(content);
}
  1. Read binary file:
string filePath = "D:\test.bin";

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    byte[] buffer = new byte[fileStream.Length];
    fileStream.Read(buffer, 0, buffer.Length);

    // 处理二进制数据
}
  1. Write binary file:
string filePath = "D:\test.bin";
byte[] data = { 0x01, 0x02, 0x03, 0x04 };

using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
    fileStream.Write(data, 0, data.Length);
}

2. Stream operation

A stream is an abstraction of data. Data can be read from a stream or written to a stream. In C#, you can use the stream classes provided by the System.IO namespace to implement stream operations.

  1. Read file stream:
string filePath = "D:\test.txt";

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    using (StreamReader streamReader = new StreamReader(fileStream))
    {
        string content = streamReader.ReadToEnd();
        Console.WriteLine(content);
    }
}
  1. Write file stream:
string filePath = "D:\test.txt";
string content = "Hello, World!";

using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        streamWriter.Write(content);
    }
}
  1. Read network stream data :
using (TcpClient client = new TcpClient("127.0.0.1", 8080))
{
    using (NetworkStream networkStream = client.GetStream())
    {
        byte[] buffer = new byte[1024];
        int bytesRead = networkStream.Read(buffer, 0, buffer.Length);

        string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
        Console.WriteLine(response);
    }
}
  1. Write network stream data:
using (TcpClient client = new TcpClient("127.0.0.1", 8080))
{
    using (NetworkStream networkStream = client.GetStream())
    {
        string request = "Hello, Server!";
        byte[] buffer = Encoding.UTF8.GetBytes(request);

        networkStream.Write(buffer, 0, buffer.Length);
    }
}

The above are sample codes for some basic file IO and stream operations. By using these codes, we can easily read and write file data, or process network stream data. Depending on specific needs, we can flexibly choose to use the file IO operation method or the stream operation method.

Summary:

File IO and stream operations in C# provide a flexible and powerful way to handle files and data streams. Whether it is reading and writing files, or processing network stream data, we only need to use the appropriate file IO operation method or stream operation method to complete the corresponding data reading and writing operations. Mastering these technologies is very important for developing applications with file and data stream processing capabilities.

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

Statement
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
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 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.

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

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

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software