C # Common IO streams and read-write files

Source: Internet
Author: User

1. File system (1) File system class The introduction file operation classes are mostly in the System.IO namespace. The FileSystemInfo class is the base class for any file system class; FileInfo and file represent files in the file system; DirectoryInfo and directory represent folders in the file system; Path represents the paths in the file system The DriveInfo provides access to information about the drive.    Note that the difference between the xxxinfo and the XXX class is that XXX is a static class, and the Xxxinfo class can be instantiated. There is a more special class System.MarshalByRefObject that allows objects to be accessed across application domain boundaries in applications that support remoting. (2) FileInfo with file class program{static void Main (string[] args) {FileInfo file = new FileInfo (@ "E:\ Learning note \c# Platform \te St.txt ");//Create File Console.WriteLine (" Create Time: "+ file.)        CreationTime); Console.WriteLine ("Path:" + file.)        DirectoryName); StreamWriter SW = file. AppendText ();//open Append stream sw. Write ("Li Zhiwei");//Append Data sw. Dispose ();//release resources, close file File.move. FullName, @ "e:\ study notes \test.txt");//Move Console.WriteLine ("Done!        ");    Console.read (); }} (3) DirectoryInfo with Directory class class program{static void Main (string[] args) {//Create folder DirectoryInfo di        Rectory = new DirectoryInfo (@ "E:\ Learning note \c# platform \test"); Directory.        Create (); Console.WriteLine ("Parent folder:" + DirectoRy.        Parent.fullname); Output all files and folders under the parent directory filesysteminfo[] files = directory.        Parent.getfilesysteminfos (); foreach (FileSystemInfo fs in Files) {Console.WriteLine (fs.        Name); } directory.delete (Directory. FullName);//Delete folder Console.WriteLine ("Done!        ");    Console.read (); }} (4) Path class program{static void Main (string[] args) {Console.WriteLine (Path.Combine (@ "E:\ Learning note \c# platform", @ "        Test\test.txt "));//Connect Console.WriteLine (" Platform-specific characters: "+ Path.directoryseparatorchar);        Console.WriteLine ("Platform-specific replacement character:" + Path.altdirectoryseparatorchar);    Console.read ();        }} (5) DriveInfo class program{static void Main (string[] args) {driveinfo[] drives = Driveinfo.getdrives (); foreach (DriveInfo d in drives) {if (D.isready) {Console.WriteLine ("Total Capacity                Volume: "+ d.totalfreespace);                Console.WriteLine ("Usable Capacity:" + d.availablefreespace); Console.wrIteline ("Drive type:" + D.driveformat);            Console.WriteLine ("Drive name:" + d.name + "\ n");        }} Console.WriteLine ("ok!");    Console.read (); }} back to top 2. File operation (1) Move, copy, delete file class program{static void Main (string[] args) {string path = @ "E:\ Learning note \c# Platform \test.t        XT ";        File.writealltext (Path, "test data"); Console.WriteLine ("The file has been created, please view!"        ");        Console.ReadLine ();        File.move (Path, @ "E:\ learning note \test.txt"); Console.WriteLine ("Mobile Complete, please check!")        ");        Console.ReadLine ();        File.Copy (@ "E:\ learning Note \test.txt", path); Console.WriteLine ("The file has been copied, please view!"        ");        Console.ReadLine ();        File.delete (path);        File.delete (@ "e:\ study notes \test.txt"); Console.WriteLine ("The file has been deleted, please view!"        \nok! ");    Console.read ();        }} (2) Determine whether the file or folder class program{static void Main (string[] args) {isfile (@ "E:\ Learning notes \c# platform \test.txt");        Isfile (@ "e:\ study notes \");        Isfile (@ "e:\ study notes \xxxxxxx");    Console.read (); }//Determine if the path is a file or folder statIC void Isfile (string path) {if (directory.exists (path)) {Console.WriteLine ("is a folder!        "); } else if (file.exists (path)) {Console.WriteLine ("is a file!        "); } else {Console.WriteLine ("Path does not exist!        "); }}} back to top 3. Read and write files with data stream (1) reading a file class program{static void Main (string[] args) {string path = @ "E:\ Learning note \c# Platform \test        . txt ";        Byte[] B = file.readallbytes (path);        Console.WriteLine ("ReadAllBytes read binary:");        foreach (byte temp in b) {Console.Write (char) temp+ "");        } string[] s = file.readalllines (path, Encoding.UTF8);        Console.WriteLine ("\nreadalllines reads all lines:");        foreach (string temp in s) {Console.WriteLine ("line:" +temp);        } string str = File.readalltext (path, Encoding.UTF8);        Console.WriteLine ("ReadAllText read all lines: \ n" + str);    Console.read ();  }} (2) Write file class program{static void Main (string[] args) {      string path = @ "E:\ Learning note \c# platform \test.txt";        File.writeallbytes (path,new byte[] {0,1,2,3,4,5,6,7,8,9});//write Binary Console.WriteLine ("WriteAllBytes Write binary Success");        Console.ReadLine ();        String[] Array = {"123", "456", "7890"};        File.writealllines (path, array, Encoding.UTF8);//write All Rows Console.WriteLine ("Writealllines writes all rows successfully");        Console.ReadLine ();        File.writealltext (Path, "ABCBEFGHIJKLMN", Encoding.UTF8);//write String Console.WriteLine ("WriteAllText write String succeeded \nok!");    Console.read ();         }} (3) the most commonly used stream classes for data flow are: FileStream: file stream, can read and write binary files.         StreamReader: A stream reader that reads characters from a byte stream in a specific encoding.         StreamWriter: A stream writer that writes characters to a stream in a specific encoding.    BufferedStream: Buffer stream To add a buffer layer to another first-class read and write operation. Hierarchy of Data Flow classes: (4) using FileStream read-write binary file class program{static void Main (string[] args) {string path = @ "E:\ Learning Note \c# Flat        Taiwan \test.txt ";        Create files as files FileStream file = new FileStream (path, filemode.createnew, FileAccess.Write); String str = "Test file--li Zhiwei";        byte[] bytes = Encoding.Unicode.GetBytes (str); File. Write (bytes, 0, bytes. LENGTH);//writes a binary file.        Dispose (); Console.WriteLine ("Write Data Success!!!"        ");        Console.ReadLine ();        Open File as read file = new FileStream (path, FileMode.Open, FileAccess.Read); byte[] temp = new byte[bytes.        Length]; File. Read (temp, 0, temp.        LENGTH);//Read binary Console.WriteLine ("Read data:" + Encoding.Unicode.GetString (temp)); File.        Dispose ();    Console.read (); }} (5) StreamWriter and StreamReader use Streamwriterstreamreader without worrying about how text files are encoded, so they are good for reading and writing text files.        Class program{static void Main (string[] args) {string path = @ "E:\ Learning note \c# platform \test.txt";        Create files as files FileStream file = new FileStream (path, FileMode.Create, FileAccess.Write);        StreamWriter SW = new StreamWriter (file); Sw.        WriteLine ("Test file-li Zhiwei"); Sw.        Dispose (); Console.WriteLine ("Write Data Success!!!"        ");        Console.ReadLine (); Open the file as a read file File = new FileStream (path, FileMode.Open, FileAccess.Read);        StreamReader sr = new StreamReader (file); Console.WriteLine ("Read data:" +SR.        ReadToEnd ()); Sr.        Dispose ();    Console.read (); }} back to top 4. Mapped memory file (1) MemoryMappedFile class (. NET4 new) When an application needs to access files frequently or randomly, it is best to use the MemoryMappedFile class (a file that maps memory). Using this method allows you to load part or all of a file into a virtual memory that is displayed to the application as if it were contained in the application's main memory. (2) Use example class program{static void Main (string[] args) {MemoryMappedFile mmfile = Memorymappedfile.createfrom        File (@ "E:\Test.txt", FileMode.OpenOrCreate, "MapName", 1024 * 1024); Memorymappedviewaccessor view = Mmfile. Createviewaccessor ();//view of the memory-mapped file//or use the data stream to manipulate the memory file//memorymappedviewstream stream = Mmfile.        Createviewstream ();        String str = "test data: Li Zhiwei!";        int length = Encoding.UTF8.GetByteCount (str); View.        Writearray<byte> (0, Encoding.UTF8.GetBytes (str), 0, length);//write data byte[] b = new Byte[length]; View.        Readarray<byte> (0, B, 0, b.length); COnsole.        WriteLine (Encoding.UTF8.GetString (b)); Mmfile.    Dispose ();//Release Resource Console.read (); }} back to top 5. File security (1) ACL describes an ACL is a table (Access control table) that exists in the computer, which enables the operating system to understand each user's access to a particular system object, such as a file directory or a single file. Each object has a security attribute defined in the Access Control table. This table has one access permission for each system user. The most common access rights include reading files (including files in all directories), writing one or more files, and executing a file (if it is an executable file or a program). (2) Read aclclass program{static void Main (string[] args) {FileStream file = new FileStream (@ "E:\Test.txt",        FileMode.Open, FileAccess.Read); FileSecurity filesec = file. GetAccessControl ();//Gets the file Access control property//Output file access Control item foreach (FileSystemAccessRule filerule in Filesec. Getaccessrules (True, True, typeof (NTAccount))) {Console.WriteLine (filerule. AccessControlType + "--" + filerule. Filesystemrights + "--" + filerule.        IdentityReference); } file.        Dispose ();    Console.read (); }} (3) Read folder Aclclass program{static void Main (string[] args) {DirectoryInfo dir= new DirectoryInfo (@ "E:\ Learning Notes        \c# platform "); DirectorySecurity filesec= dir. GetAccessControl ();//Gets the file Access control property//Output file access Control item foreach (FileSystemAccessRule filerule in Filesec. Getaccessrules (True, True, typeof (NTAccount))) {Console.WriteLine (filerule. AccessControlType + "--" + filerule. Filesystemrights + "--" + filerule.        IdentityReference);    } console.read (); }} (4) modify Aclclass program{static void Main (string[] args) {FileStream file = new FileStream (@ "E:\Test.txt", F        Ilemode.open, FileAccess.Read); FileSecurity filesec = file. GetAccessControl ();//Get File Access control Properties Print (filesec.            Getaccessrules (True, True, typeof (NTAccount)));//Output File access control entry FileSystemAccessRule rule = new FileSystemAccessRule ( New NTAccount (@ "CENTER-YFB-512\LIZW"),//Computer account name Filesystemrights.delete,//Operation permissions Accesscontr Oltype.allow);//can access the protected object filesec. Addaccessrule (rule);//Add ACL entry Print (filesec. Getaccessrules (True, True, typeof (NTAccount)));//Output File access control entry filesec. Removeaccessrule (rule);//Remove ACL entry Print (filesec. Getaccessrules (True, True, typeof (NTAccount)));//Output File access control entry.        Dispose ();    Console.read (); }//Output file access control entry static void Print (Authorizationrulecollection rules) {foreach (FileSystemAccessRule Filerul E in rules) {Console.WriteLine (filerule. AccessControlType + "--" + filerule. Filesystemrights + "--" + filerule.        IdentityReference);    } Console.WriteLine ("================================================"); }} back to top 6. Read and Write Registry (1) The registry describes the Windows registry as a set of data files that help Windows control hardware, software, user environments, and Windows interfaces, and run Regedit to see 5 registry hives (actually 7): Hkey-clas Ses-root: File association and COM information hkey-current-user: User profile Hkey-local-machine: Local machine system global configuration sub-key Hkey-user S: User profile subkey loaded Hkey-current-config: Current hardware configuration (2). NET operation of the registry provides the registry class, the RegistryKey class, in. NET, to implement operations on the registry. Where the Registry class encapsulates the Registry's seven basic keys: Registry.classesroot corresponds to the HKEY_CLASSES_ROOT primary key registry.currentuser corresponds to HKEY_CU RrEnt_user primary key Registry.localmachine corresponds to HKEY_LOCAL_MACHINE PRIMARY KEY Registry.user corresponds to Hkey_user primary key The registry.currentconfig corresponds to the Heky_current_config primary key Registry.dynda corresponds to the Hkey_dyn_data primary key Registry.per Formancedata corresponds to the Hkey_performance_data primary key RegistryKey class encapsulates the basic operation of the registry, including reading, writing, and deleting.         The main functions that are read are: OpenSubKey () is mainly to open the specified subkey.         Getsubkeynames () Gets the name of all subkeys below the primary key, and its return value is an array of strings.         GetValueNames () gets all the key names in the current subkey, and its return value is also an array of strings.    GetValue () specifies the key value of the key.      Function written: CreateSubKey () adds a subkey SetValue () to set the key value of a key delete function: DeleteSubKey () deletes a specified subkey. Deletesubkeytree () deletes the subkey and all subkeys below the subkey. (3) Example class program{static void Main (string[] args) {string path = @ "Software\Microsoft\Internet Explorer\ex        Tensions ";            RegistryKey Pregkey = Registry.LocalMachine.OpenSubKey (path, true);//in read-only mode if (Pregkey! = null) { Console.WriteLine (Pregkey. Name + "--" + Pregkey. SubKeycount + "--" + Pregkey.            Valuecount); String prename = System.Guid.NewGuid ().            ToString (); Pregkey. CreateSubKey (prename);//Add a sub-key RegistryKey New_pregkey = Registry.LocalMachine.OpenSubKey (path + @ "\" + prename            , true); New_pregkey. SetValue ("name", "Li Zhiwei");//sets the key value of a key new_pregkey. SetValue ("Key Name", "Value content");//Set key value of a key Console.WriteLine (Pregkey. Name + "--" + Pregkey. Subkeycount + "--" + Pregkey.            Valuecount); Pregkey.            Close (); New_pregkey.        Close ();    } console.read (); }} back to top 7. Read-Write independent memory (1) The IsolatedStorageFile class can read and write independent memory using the IsolatedStorageFile class, and the isolated memory can be viewed as a virtual disk.    In which you can save data items that are shared only by the application that created them or their application program instances. There are two types of access for isolated storage (e.g.): the first is that multiple instances of an application work in the same isolated memory, and the second is that multiple instances of an application work in separate, isolated storage.  (2) example class program{static void Main (string[] args) {//write file IsolatedStorageFileStream storstream = new        IsolatedStorageFileStream (@ "Test.txt", FileMode.Create, FileAccess.Write); String str = "test data: Li Zhiwei! ABCD ";        byte[] bs = Encoding.UTF8.GetBytes (str); Storstream.write (BS, 0, BS.        LENGTH);//write Data storstream.dispose ();        Read file IsolatedStorageFile storfile = Isolatedstoragefile.getuserstorefordomain ();        String[] Files=storfile.getfilenames (@ "Test.txt");            foreach (String t in files) {Console.WriteLine (t);            Storstream = new IsolatedStorageFileStream (t, FileMode.Open, FileAccess.Read);            StreamReader sr=new StreamReader (Storstream); Console.WriteLine ("Read file:" +SR.            ReadToEnd ()); Sr.            Dispose ();        Storfile.deletefile (t);//delete file} storfile.dispose ();        Console.WriteLine ("ok!");    Console.read (); }}------------------------------------------------------------------------------------------------------------- ------------------

C # Common IO streams and read-write files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.