C# file input and output
A file is a collection of data stored on disk with a specified name and directory path. When a file is opened for reading or writing, it becomes a stream.
Fundamentally, a stream is a sequence of bytes passed over a communication path. There are two main streams: input stream and output stream. The input stream is used to read data from the file (read operation), and the output stream is used to write data to the file (write operation).
C# I/O Classes
The System.IO namespace has various different classes that are used to perform various file operations such as creating and deleting files, reading or writing files, closing files, etc.
The following table lists some commonly used non-abstract classes in the System.IO namespace:
I/O Class
Description
BinaryReader Read raw data from a binary stream.
BinaryWriter Writes raw data in binary format.
BufferedStream Temporary storage of byte stream.
Directory Helps in manipulating the directory structure.
DirectoryInfo is used to perform operations on directories.
DriveInfo Provides drive information.
File helps with file processing.
FileInfo is used to perform operations on files.
FileStream is used to read and write anywhere in the file.
MemoryStream is used for random access to the data stream stored in memory.
Path Perform operations on path information.
StreamReader is used to read characters from a byte stream.
StreamWriter is used to write characters to a stream.
StringReader is used to read the string buffer.
StringWriter is used to write to the string buffer.
FileStream class
The FileStream class in the System.IO namespace helps in reading, writing and closing files. This class is derived from the abstract class Stream.
You need to create a FileStream object to create a new file, or open an existing file. The syntax for creating a FileStream object is as follows:
FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
For example, create a FileStream object F to read a file named sample.txt:
FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
Parameters
Description
FileMode
FileMode enumeration defines each A way to open a file. The members of the FileMode enumeration are:
Append: Open an existing file and place the cursor at the end of the file. If the file does not exist, create the file.
Create: Create a new file. If the file already exists, the old file is deleted and the new file is created.
CreateNew: Specifies that the operating system should create a new file. If the file already exists, an exception is thrown.
Open: Open an existing file. If the file does not exist, an exception is thrown.
OpenOrCreate: Specifies that the operating system should open an existing file. If the file does not exist, a new file is created with the specified name and opened.
Truncate: Open an existing file. Once the file is opened, it will be truncated to zero byte size. We can then write completely new data to the file but retain the original creation date of the file. If the file does not exist, an exception is thrown.
FileAccess
FileAccess The members of the enumeration are: Read, ReadWrite and Write.
FileShare
FileShare The members of the enumeration are:
Inheritable: allows file handles to be inherited by child processes. Win32 does not directly support this feature.
None: Do not share the current file. Any request to open the file (from this process or another process) will fail until the file is closed.
Read: Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (from this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions may be required to access the file.
ReadWrite: Allows the file to be subsequently opened for reading or writing. If this flag is not specified, any request to open the file for reading or writing (from this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions may be required to access the file.
Write:允许随后打开文件写入。如果未指定此标志,则文件关闭前,任何打开该文件以进行写入的请求(由此进程或另一进过程发出的请求)都将失败。但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。
Delete:允许随后删除文件。
实例
下面的程序演示了 FileStream 类的用法:
using System; using System.IO; namespace FileIOApplication { class Program { static void Main(string[] args) { FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) { F.WriteByte((byte)i); } F.Position = 0; for (int i = 0; i <= 20; i++) { Console.Write(F.ReadByte() + " "); } F.Close(); Console.ReadKey(); } } }
当上面的代码被编译和执行时,它会产生下列结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
C# 高级文件操作
上面的实例演示了 C# 中简单的文件操作。但是,要充分利用 C# System.IO 类的强大功能,您需要知道这些类常用的属性和方法。
在下面的章节中,我们将讨论这些类和它们执行的操作。请单击链接详细了解各个部分的知识:
主题
描述
文本文件的读写 它涉及到文本文件的读写。StreamReader 和 StreamWriter 类有助于完成文本文件的读写。
二进制文件的读写 它涉及到二进制文件的读写。BinaryReader 和 BinaryWriter 类有助于完成二进制文件的读写。
Windows 文件系统的操作 它让 C# 程序员能够浏览并定位 Windows 文件和目录。
以上就是【c#教程】C# 文件的输入与输出的内容,更多相关内容请关注PHP中文网(www.php.cn)!

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

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

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

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 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.

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.

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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),