In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use the File static class in C# to read and write to the file". In the daily operation, I believe that many people have doubts about how to use the File static class in C# to read and write the file. Xiaobian consulted all kinds of data and sorted out a simple and easy-to-use method of operation. I hope it will be helpful for you to answer the doubt of "how to use the File static class in C# to read and write the file". Next, please follow the editor to study!
Provides static methods for creating, copying, deleting, moving, and opening a single file, and assists in creating FileStream objects.
First, read the document:
1. Return string:
String readText = File.ReadAllText (@ "c:\ temp\ MyTest.txt")
2. Return an array of strings:
String [] readText = File.ReadAllLines (@ "c:\ temp\ MyTest.txt", Encoding.UTF8)
3. Return byte array:
Byte [] buffer = File.ReadAllBytes (@ "c:\ temp\ MyTest.txt"); string str = Encoding.Default.GetString (buffer, 0, buffer.Length)
4. Return StreamReader
Open existing UTF-8 text for reading
Using (StreamReader sr = File.OpenText (@ "c:\ temp\ MyTest.txt") {string s; while ((s = sr.ReadLine ())! = null) {Console.WriteLine (s);}} II. Write the file.
Create a new file to write to it. If the file already exists, it will be overwritten.
1. Write a string:
String createText = "Hello and Welcome" + Environment.NewLine;File.WriteAllText (path, createText); / / File.WriteAllText (), File.AppendAllText ()
2. Write an array of strings:
String [] createText = {"Hello", "And", "Welcome"}; File.WriteAllLines (path, createText)
3. Write byte array:
String str = "ha"; byte [] buffer = Encoding.Default.GetBytes (str); File.WriteAllBytes (path,buffer)
4. Return StreamWriter
Create or open existing UTF-8 text for writing or appending
Using (StreamWriter sw = File.CreateText (path)) / / StreamWriter:File.CreateText (), File.AppendText () {sw.WriteLine ("Hello"); sw.WriteLine ("And"); sw.WriteLine ("Welcome");} III. Operation that returns FileStream
File.Open (): does not share by default and has read / write access
Using (FileStream fs = File.Open (path, FileMode.Open, FileAccess.Read, FileShare.None) {byte [] b = new byte [1024]; UTF8Encoding temp = new UTF8Encoding (true); while (fs.Read (b, 0, b.Length) > 0) {Console.WriteLine (temp.GetString (b));}}
File.OpenRead (): read access
Slightly
File.OpenWrite: write access
Using (FileStream fs = File.OpenWrite (path)) {Byte [] info = new UTF8Encoding (true) .GetBytes ("This is to test the OpenWrite method."); / / Add some information to the file. Fs.Write (info, 0, info.Length);}
File.Create ():
Using (FileStream fs = File.Create (path)) {Byte [] info = new UTF8Encoding (true) .GetBytes ("This is some text in the file."); / / Add some information to the file. Fs.Write (info, 0, info.Length);} IV. Common operations of the File class:
File deletion method: File.Delete ()
File copy method: File.Copy ()
File movement method: File.Move ()
Set file properties method: File.Set/Get*** ()
The method to determine whether a file exists: File.Exist ()
5. Common operations of directory class: / / delete this directory Directory.Delete (@ "C:\ new folder") / / delete this directory. True means that if this directory has subdirectories also deleted, otherwise, an exception Directory.Delete (@ "C:\ new folder", false) will be thrown; / / whether this directory exists bool b = Directory.Exists (@ "C:\ new folder"). / / return the subdirectory under this directory string [] dirs1 = Directory.GetDirectories (@ "C:\ new folder") according to the path; / / the second parameter indicates the scope of the search, that is, the search folder contains the "basic" keyword string [] dirs2 = Directory.GetDirectories (@ "C:\ new folder", "basic"). / / search all files in the directory string [] files = Directory.GetFiles (@ "C:\ New folder"); / / the third parameter indicates that the search operation should include all subdirectories or only the current directory. String [] files1 = Directory.GetFiles (@ "C:\ New folder", "2.txt", SearchOption.AllDirectories); / / (returns an array of DirectoryInfo when getting all directories under the specified directory. ) DirectoryInfo dirs = Directory.GetParent (@ "C:\ New folder"); / / move, cut. Can only be on the same disk. The directory does not have a Copy method. You can use the Move () method to rename. Directory.Move (@ "F:\ test\ 33", @ "F:\ test\ 32\ 33"); VI. FileSystemInfo
Derived class:
DirectoryInfo
FileInfo
1. FileInfo class / / instantiate FileInfo to operate FileInfo myfile = new FileInfo (path); / / declare an object to operate on a file myfile.CopyTo (destpath); / / copy a pair of files with the path destpathmyfile.MoveTo (destpath); / / move myfile.Delete () / / perform delete operation / / get the details of a file or folder (creation date, last modified date, etc.) FileInfo myfile = new FileInfo (path); / / declare an object to operate on a file DateTime dt = myfile.CreationTime; / / get or set the creation date of the file / folder string filepath = myfile.DirectoryName / / can only be used for FileInfo, get the full pathname, path + file name bool file = myfile.Exists; / / the value of this attribute indicates whether the file or folder exists, and if it exists, it will return Truestring fullname = myfile.FullName; / / get the full pathname of the file or folder DateTime lastTime = myfile.LastAccessTime; / / get or set the time when the file or folder was last accessed DateTime lastWrite = myfile.LastWriteTime / / get or set the time when the folder or folder was last modified string name = myfile.Name; / / get the file name. Cannot modify oh long length = myfile.Length; / / the byte size / / CreationTime,LastAccessTime,LastWriteTime of the returned file can be modified. 2. DirectoryInfo class DirectoryInfo dir = new DirectoryInfo (@ "d:\ C # programming"); if (! dir.Exists) {dir.Create ();} else {Console.WriteLine ("this directory already exists");} VII. DriveInfo class
In the Windows operating system, the storage medium is collectively referred to as the drive. Because the hard disk can be divided into multiple areas, each area is called a drive.
Common field members of the DriveInfo class are
DriveFormat (file system format, such as NTFS or FAT32),
DriveType (drive type),
Name (drive name),
TotalSize (total space),
TotalFreeSpace (get free space for the drive).
A common method member is GetDrives (get a list of available drives).
DriveType enumerated values include CDRom (optical drive), Fixed (hard disk), Network (network drive), and Removeable (floppy disk or USB disk).
For example, the following code can output the remaining space information for each hard drive.
DriveInfo [] drivers = DriveInfo.GetDrives (); foreach (DriveInfo driver in drivers) {if (driver.DriveType = = DriveType.Fixed & & driver.DriveFormat = = "NTFS") {Console.WriteLine ("there is {1} byte space left on the {0} drive." , driver.Name, driver.AvailableFreeSpace);}} at this point, the study on "how to read and write files with File static classes in C#" is over. I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.