当前位置:网站首页>[C] file operation
[C] file operation
2022-04-22 05:18:00 【Pistachio 2021】
When manipulating variables and constants , Data is stored in memory , After the program runs, it will be completely deleted . Want to save data for a long time , You can choose files or databases to store .
C# Provides DriveInfo、Directory、DirectoryInfo、File、FileInfo、Path File operation class , To create files when the program is running 、 Reading and writing 、 Moving and so on .
One 、DriveInfo
Sealing class , Used to view computer drive information . It mainly includes checking the disk space 、 File format of disk 、 Volume label of disk, etc .
Driveinfo driveInfo=new Driveinfo("C");
Common properties and methods :
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
DriveInfo driveInfo = new DriveInfo("D");
Console.WriteLine(" Name of the drive :" + driveInfo.Name);
Console.WriteLine(" The root directory of the drive :" + driveInfo.RootDirectory);
Console.WriteLine(" Whether the drive is ready :" + driveInfo.IsReady);
Console.WriteLine(" Amount of free space available on disk :" + driveInfo.AvailableFreeSpace);
Console.WriteLine(" Total free space available on drive :" + driveInfo.TotalFreeSpace);
Console.WriteLine(" Total storage space on drive :" + driveInfo.TotalSize);
Console.WriteLine(" File system format name :" + driveInfo.DriveFormat);
Console.WriteLine(" Drive type :" + driveInfo.DriveType);
Console.WriteLine(" The volume label of the drive :" + driveInfo.VolumeLabel);
Console.ReadLine();
}
}
}

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Get all drive names and file formats in your computer
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
Console.WriteLine(" Drive name :" + drive.Name);
Console.WriteLine(" File format :" + drive.DriveFormat);
}
}
Console.ReadLine();
}
}
}

Two 、DirectoryInfo
stay C# in Directory Classes and DirectoryInfo Classes operate on folders .
DirectoryInfo Class provides a constructor , The grammatical form is as follows :
DirectoryInfo(string path)
ad locum path Parameter is used to specify the directory of the file , I.e. path .
For example, the creation path is D On the plate test Instance of folder , The code is as follows .
DirectoryInfo directoryInfo = new DirectoryInfo("D:\\test");
It should be noted that if... Is used in the path \, Use escape characters to represent , namely \\; Or in the path \ Character to /.


3、 ... and 、Directory
Directory Class is a static class , Cannot create an instance of this class , Directly through “ Class name . Members of the class ” Call its properties and methods as .
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Use Directory Class in D On disk operation code Folder , It is required to judge whether the folder exists first , Delete... If it exists , Otherwise, create the folder
if (Directory.Exists(@"D:\code"))
Directory.Delete(@"D:\code",true);
else
Directory.CreateDirectory(@"D:\code");
}
}
}
Four 、FileInfo
C# in File Classes and FileInfo Classes are used to manipulate files , And the effect is similar , Can complete the creation of files 、 Change file name 、 Delete file 、 Moving files, etc .
static void Main(string[] args)
{
// stay D Discoid code Create a folder named test1.txt The file of , And get the relevant attributes of the file , Then move it to D On the plate code-1 In the folder .
Directory.CreateDirectory(@"D:\code");
FileInfo fileInfo = new FileInfo(@"D:\code\test1.txt");
if (!fileInfo.Exists)
fileInfo.Create().Close();// create a file .Close() Close the stream and release all resources associated with it
fileInfo.Attributes = FileAttributes.Normal;
Console.WriteLine(" file name :" + fileInfo.Name);
Console.WriteLine(" File parent directory :" + fileInfo.Directory);
Console.WriteLine(" Full directory of files :" + fileInfo.FullName);
Console.WriteLine(" Full path to directory :" + fileInfo.DirectoryName);
Console.WriteLine(" File creation time :" + fileInfo.CreationTime);
Console.WriteLine(" File extension :" + fileInfo.Extension);
Console.WriteLine(" Whether the file is read-only :" + fileInfo.IsReadOnly);
Console.WriteLine(" Last accessed file time :" + fileInfo.LastAccessTime);
Console.WriteLine(" Last write file time :" + fileInfo.LastWriteTime);
Console.WriteLine(" file size :" + fileInfo.Length);
Console.ReadLine();
Directory.CreateDirectory(@"D:\code-1");// establish code-1 Folder
FileInfo newFileInfo = new FileInfo(@"D:\code-1\test1.txt");// Judge code-1 Whether there is... Under the folder test1.txt
if (!newFileInfo.Exists)
fileInfo.MoveTo(@"D:\code-1\test1.txt");// If it doesn't exist, move the file
}
}
}
5、 ... and 、Path
For a file or directory that contains path information System.String Static classes that operate on instances .
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// Enter a path from the console , Output the path without extension of the path 、 Extension 、 Full file name 、 File path 、 Change file extension
Console.WriteLine(" Please enter a path :");
string path = Console.ReadLine();
Console.WriteLine(" Path without extension :" + Path.GetFileNameWithoutExtension(path));
Console.WriteLine(" Extension :" + Path.GetExtension(path));
Console.WriteLine(" Full file name :" + Path.GetFileName(path));
Console.WriteLine(" File absolute path :" + Path.GetFullPath(path));
Console.WriteLine(" File path :" + Path.GetDirectoryName(path));
Console.WriteLine(" Change file extension :" + Path.ChangeExtension(path, null));
Console.ReadLine();
}
}
}
6、 ... and 、 flow
The flow in the computer is actually a kind of information transformation , It's an ordered flow . Relative to an object , Usually, we call the object receiving external information input as input stream (Input) , The output stream from the object to the outside world is called the output stream (Output). Collectively referred to as input / Output stream (I/O Streams).
When exchanging information or data between objects, always convert the information or data into some form of flow first , Transfer via stream , After reaching the destination object, the stream is converted into object data .
therefore , Stream can be regarded as a carrier of data , Used to realize data transmission and exchange .
The namespace of the stream is also System.IO, It mainly includes the reading and writing of text files 、 Reading and writing of image and sound files 、 Reading and writing of binary files, etc .
Stream is an abstract concept of byte sequence , Such as files 、 Input / Output devices 、 Internal process communication pipeline, etc .
Stream provides a way to write bytes to and read bytes from backing memory .
In addition to file streams directly related to disk files , There are many other types of streams .
For example, data streams (Stream) , It is an abstract representation of serial transmission data , It's about input / An abstraction of output .
Data has source and destination , Connecting the two is the streaming object .
If you take the data from the source , You can try to enter ( read ) Streaming , Store data in memory buffer ; If you write data to the destination , You can use output ( Write ) Streaming , Write the data in the memory buffer to the destination .
When you want to transmit data over the network , Or when operating on file data , First, you need to convert the data into a data stream .
A typical data flow is related to an external data source , The data source can be a file 、 Peripheral 、 Memory 、 Network socket, etc .
Depending on the data source ,.Net Provides multiple from Stream Subclasses derived from class , Each class represents a specific data flow type , For example, the file stream class directly related to disk files FileStream, Network stream class related to socket NetworkStream, Memory stream class related to memory MemoryStream etc. .
7、 ... and 、StreamReader
C# in StreamReader Class is used to read a string from a stream
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Directory.CreateDirectory(@"D:\code");
File.Create(@"D:\code\test.txt").Close();
// Read D disc code Under the folder test.txt Information in the file .
string path = @"D:\code\test.txt";
StreamReader reader = new StreamReader(path);
if (reader.Peek() != -1)// Determine whether there are characters in the file
{
string str = reader.ReadLine();
Console.WriteLine(str);
Console.ReadLine();
}
reader.Close();
}
}
}


When reading the information in the file , Except that it can be used ReadLine Out of the way , You can also use Read、ReadToEnd Method
8、 ... and 、StreamWriter
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// towards D disc code The folder test.txt Write your name and mobile number in the file
string path = @"D:\code\test.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine(" full name ");
writer.WriteLine(" Phone number ");
writer.Flush();// Refresh cache
}
}
}
}
Nine 、FileStream
It is mainly used for reading and writing files , Not only can I read and write ordinary text files , You can also read image files 、 Files in different formats such as sound files .
Creating FileStream Class will also involve the values of multiple enumeration types , Include FileAccess、FileMode、FileShare、FileOptions etc. .
FileAccess Enumeration types are mainly used to set file access methods :
- Read: Open the file read-only .
- Write: Open the file in write mode .
- ReadWrite: Open the file read-write
FileMode Enumeration type is mainly used to set the way to open or create files :
- CreateNew: Create a new file , If the file already exists , An exception will be thrown .
- Create: create a file , If the file exists , Then delete the original file , Recreate the file .
- Open: Open an existing file , If the file doesn't exist , An exception will be thrown .
- OpenOrCreate: Open an existing file , If the file doesn't exist , Create file .
- Truncate: Open an existing file , And clear the contents of the file , Keep the creation date of the file . If the file doesn't exist , An exception will be thrown .
- Append: Open file , Used to append content to a file , If the file doesn't exist , Create a new file .
FileShare Enumeration type is mainly used to set the access control when multiple objects access the same file at the same time :
- None: Declined to share the current file .
- Read: Allow subsequent opening of files to read information .
- ReadWrite: Allow subsequent opening of files to read and write information .
- Write: Allow subsequent opening of files to write information .
- Delete: Allow subsequent deletion of files .
- Inheritable: Make file handles inheritable by child processes .
FileOptions Enumeration types are used to set advanced options for files , Including whether the file is encrypted 、 Whether to delete after access, etc :
- WriteThrough: Indicates that the system should pass through any intermediate cache 、 Write directly to disk .
- None: Indicates that... Is being generated System.IO.FileStream Object should not be used with other options .
- Encrypted: Indicates that the file is encrypted , It can only be decrypted through the same user account used for encryption .
- DeleteOnClose: Indicates that a file is automatically deleted when it is no longer in use .
- SequentialScan: Indicates that files are accessed from beginning to end .
- RandomAccess: Indicates random access to files .
- Asynchronous: Indicates that the file can be used for asynchronous read and write .
class Program
{
static void Main(string[] args)
{
// stay D disc code The folder student.txt Write the student number information in the file
File.Create(@"D:\code\student.txt").Close();
string path = @"D:\code\student.txt";
string mes = " Student number :3188906224";
byte[] bytes = Encoding.UTF8.GetBytes(mes);// Convert data from string type to byte type
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Write))
{
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush();
}
// from D Discoid code In the folder student.txt The student number in the file is read out , And display it on the console
if (File.Exists(path))
{
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
byte[] b = new byte[fileStream.Length];// Define the byte array for storing file information
fileStream.Read(b, 0, b.Length);// Read file information
char[] c = Encoding.UTF8.GetChars(b);// Convert the read data from byte type to character type
Console.WriteLine(c);
}
}
else
Console.WriteLine(" file does not exist ");
Console.ReadLine();
}
}
}

Ten 、BinaryReader
11、 ... and 、BinaryWriter
版权声明
本文为[Pistachio 2021]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210625511796.html
边栏推荐
- Drawing scatter diagram with MATLAB
- Learn from me: how to release your own plugin or package in China
- Input and output of scanf and printf (format controller)
- JUnit assertion
- 2022-1-17 to 2022-1-30 iterator mode
- JUnit common notes
- Why choose B + tree as the underlying engine of MySQL: (3.28-4.3)
- VIM is so difficult to use, why are so many people keen?
- Chapter 3 basic SQL syntax
- PyTorch搭建双向LSTM实现时间序列预测(负荷预测)
猜你喜欢

One way to disable Google cross domain

Swagger UI简介

VIM is so difficult to use, why are so many people keen?

Junit简介与入门

Error: ER_ NOT_ SUPPORTED_ AUTH_ MODE: Client does not support authentication protocol requested by serv
![[I. XXX pest detection items] 3. Loss function attempt: focal loss](/img/91/5771f6d4b73663c75da68056207640.png)
[I. XXX pest detection items] 3. Loss function attempt: focal loss

Meetup 02期回顾:Q&A 集锦

Uninstallation, installation and setting of MySQL

Nexus private server - (II) console installation of version 3.2.0, initial password location

Supplement to the usage of permute() function in torch (detailed process of matrix dimension change)
随机推荐
Junit簡介與入門
Summary of database Deadlock: (3.7-3.13)
MySQL encoding problem
【CANdelaStudio编辑CDD】-2.3-实现$27服务多个SecurityLevel之间的跳转(UDS诊断)
TDD development mode and DDD development mode
物联网测试都有哪些挑战,软件检测机构如何保证质量
Temperature control via mqc582tt + PNET
JSON class of Delphi: superobject, and simple usage jsonhelper
Supplement to the usage of permute() function in torch (detailed process of matrix dimension change)
防抖函数和节流函数
Garbled code in Web Applications
Error: ER_ NOT_ SUPPORTED_ AUTH_ MODE: Client does not support authentication protocol requested by serv
Log4 log framework
Vs2019 official free print control
Feign calls the service, and the called service Seata transaction is not opened or XID is empty
Usage of swagger and common annotation explanation
Jackson
Restful style API design
Reduce the graduation time to before the age of 20, and go to primary school for five years at the age of 5, so as to increase the population
[boutique] using dynamic agent to realize unified transaction management