Home  >  Article  >  Backend Development  >  [C# Tutorial] C# file input and output

[C# Tutorial] C# file input and output

黄舟
黄舟Original
2016-12-24 13:32:281269browse

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)!


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