C # Language---File read-write operations

Source: Internet
Author: User

file read and write operationsThere are different types of System.IO named spaces, used to perform various file operations 1.File categoryProvides a way to create, duplicate, delete, move, and open a single file. Some methods of Flie can be used to return FileStream and StreamWriter-like methods:
    • Open (String path,filemode mode) read/write the FileStream parameters on the specified path path to open the file mode is used when the specified file does not exist, whether to create the file, and to make sure that the reservation is covered
    • Create (String) to create or overwrite files in a specified path
    • Copy (string,string) copies the file to a new file, forbid the file with the same name
    • Delete (string path) removes the specified file
    • Move (String sourcefilename,string destfilename) (the name of the file to be moved, including the opposite or absolute path, the new path and name of the file)
    • SetAttributes (string path, FileAttributes fileattributes) set file (read only, hide)
    • Exist (string path) to make sure that the specified file exists

Read and write:

    • ReadAllLines (string,encoding) Open a file, use the specified code to read all the lines of the file (to open the file to be read, the document will be used to encode the content)
    • ReadAllText (string,encoding) Open a text file that reads all the lines of the file using the specified encoding
    • Writealllines (String path,string[] contents) Creates a new file in which to write the specified set of characters, and then close the file (the files to be written, the string of files to be written into)
    • WriteAllText (string path,string contents) writes the specified string
namespacefiletest{classFiletest {Static voidMain (string[] args) {            stringPath =@"D:\YGTfiletest\filetest.txt";//file path            Try            {                using(FileStream fs = file.create (path))//use using, defining ranges, recovering resources at the end of the range, creating files in the specified path{byte[] info=NewUTF8Encoding (true). GetBytes ("some text in the file"); //into a word, write the numbers.Fs. Write (Info,0, info. Length);//Word Count , offset, maximum number of characters to write                }                using(StreamReader sr = file.opentext (path))//Open File                {                    strings ="";  while(s = Sr. ReadLine ())! =NULL)//Read file contents{Console.WriteLine (s); }                }                if(file.exists (path))//whether the file exists                {                    stringAppendText ="Add Content"+ Environment.NewLine;//environment is a class, NewLine is a string property that gets the carriage return newline character string defined in the current environment. As for \ r \ nFile.writealltext (path, appendtext);//writes the specified string                    stringReadText = File.readalltext (path);//open a text file and read all the lines of the file using the specified encodingConsole.WriteLine (ReadText); string[] CreateText = {"A","B","C" }; File.writealllines (path, createtext); //string numbers of files written into the file                    stringREADTEXT2 =file.readalltext (path);                    Console.WriteLine (READTEXT2); string[] readText3 = file.readalllines (path);//Reads all the rows of a file, returning an array of strings containing all the rows of the file.                     foreach(stringSinchreadText3)                    {Console.WriteLine (s);                } console.readkey (); }            }            Catch(Exception ex) {Console.WriteLine (ex).            ToString ()); }        }    }}

2. FileStream file stream

File stream FileStream is used in the operation of file stream, and the file type of the operation of the document method is different, FileStream can manipulate the word can be saved any kind of file, solve the problem (operation of large files)

The nature of the metal:

    • CanRead to determine whether the previous stream supports reading, returns a bool value
    • CanWrite to determine if the previous stream supports write-in, returns a bool value

Method:

    • Read () reads the numbers from the stream, returns the word count
    • ReadByte () reads a word from the stream and advances the position in the stream by one word.
    • Write () writes the word block (word count) into the stream
    • WriteByte () writes a word to the current position in the stream and advances the position in a word
    • Seek () Set the starting position of the file to read or write into
    • Flush () clears the stream buffer so that all the buffer numbers are written into the file
    • Close () closes the current stream and releases all the system resources associated with it
File Interview Method (FileAccess)
    • FileAccess.Read to the file.
    • FileAccess.Write write operations on files
    • FileAccess.ReadWrite to read or write to a file.

File open mode (FileMode)

    • Filemode.append open a file to append to the file, only with FileAccess.Write.
    • FileMode.Create creates new documents, if they exist, cover
    • FileMode.CreateNew creates new documents, if they exist, they are often
    • FileMode.OpenOrCreate Open the file, if not, create
    • Fliemode.truncate Open the file, and empty the file content
namespacestream{classStream {Static voidMain (string[] args) {            //Create FileStream, enter the path, open mode, and interview methodFileStream Fsread =NewFileStream (@"D:\YGTfiletest\filestream.txt", Filemode.openorcreate,fileaccess.read); //word count, size 5M            byte[] buffer =New byte[1024x768*1024x768*5]; //returns the number of characters that are actually read            intR = Fsread. Read (Buffer,0, buffer.            Length); //Console.WriteLine (R); //Console.readkey (); //encode each element in the buffer to the city string            strings = Encoding.Default.GetString (buffer,0, R); //ReleasingFsread.            Close (); //the source of the released informationFsread.            Dispose ();                       Console.WriteLine (s); using(FileStream fswrite =NewFileStream (@"D:\YGTfiletest\filestream.txt", FileMode.OpenOrCreate, FileAccess.Write)) {                stringstr ="AAAA"; byte[] Buffe =Encoding.Default.GetBytes (str); Fswrite.write (Buffe,0, Buffe.            Length); } Console.WriteLine ("has been written into");        Console.readkey (); }    }}

3.MemoryStream Internal Stream (Read, ReadByte, Write, WriteByte)

The MemoryStream represents a stream of stored memory that can be directly visited in the memory by the stored stream. The memory is generally used to reduce the need for the application to the immediate buffer zone and the file stream. Unlike file streams, the numbers in the stored stream are stored in the memory in the form of a number of symbols, and the system can directly access these assemblies without having to read the magnetic plates. Read faster. MemoryStream of the Metal:
    • CanRead A value that indicates whether the current stream supports reading
    • CanSeek A value that indicates whether the previous stream supports finding
    • Cantimeout support for extra time
    • Whether CanWrite supports write-in
    • Capacity the number of characters assigned to the stream by the Access or setup
    • Length of the stream represented by the word
    • Position the current position in the access or setup stream
MemoryStream Method:
    • Beginread/endread to start an interracial step-by-step
    • Beginwrite/endwrite start the operation/end of the interracial
    • Read reads a word from the current stream and writes the numbers into buffer (starting from the position of the position of the current stream)
    • ReadByte read a Word
    • Seek to set the length of the current stream as the specified value
    • Write uses the numbers read from the buffer to write the word stream into the current
    • WriteByte writes a word to the current position in the previous stream
    • WriteTo writes the entire contents of this stored stream into another stream (the internal flow flows to other streams)
namespaceconsoleapplication1{classMemoryStream1 {Static voidMain (string[] args) {MemoryStream ms=NewMemoryStream (); byte[] buffer = Encoding.UTF8.GetBytes ("ABCDEFG");//Number of Word episodesMs. Write (Buffer,0,7);//Read The numbers from the cache and write the stream            byte[] result = Ms. GetBuffer ();//returns the source of the stream that was written into the flow            stringTurnstr = Encoding.UTF8.GetString (result);//Convert a Word count to a stringConsole.WriteLine (TURNSTR); Ms. Seek (0, Seekorigin.begin);//Set the current position of the stream to start            inti = Ms. ReadByte ();//Read A word, if you reach the end of the stream-1, return the ASCII code of the wordConsole.WriteLine ("current position of the stream", i.ToString ()); byte[] Result1 = Ms. ToArray ();//Stream Returns a word count, buffer zone, similar to GetBuffer            foreach(varIteminchresult1) {Console.Write (item. ToString ()+"-"); } MemoryStream MS2=NewMemoryStream (); byte[] Buffer2 = Encoding.UTF8.GetBytes ("Han characters account for three characters"); MS2. Write (Buffer2,0, Buffer2. Length);//source, index, lengthConsole.WriteLine ("\ n"+ms2. Position);//position can be understood as a needle, and after writing the numbers in the last            intj = Ms2. ReadByte ();//The index position in the last bit, so the returned value is-1, which indicates the lastConsole.WriteLine ("the value that was pointed to when the previous pin was written: {0}", j.tostring ()); MS2. Position=0; intK =MS2.            ReadByte (); Console.WriteLine ("change the value after the needle: {0}", k.tostring ());        Console.readkey ();                                                                                                                                                                                                                                  }} Output Results ABCDEFG Current position of the stream $- the- the- the- the- -- in- +the value that the previous pointer points to when it is written into the numbers:-1to change the value after the needle: the

4. Stream writer (writer, writerline)

With FileStream, which requires a lot of extra digital conversion work, Stream writer allows the characters and strings to be written directly into the file without having to be converted into a word, which is generally not the same as the binary and the creative FileStream, The creation of StreamWriter does not provide a group of choices, and does not specify FileMode, FileAccess as FileStream, and is always subject to the right to read the file. So to use the high-level parameters, first specify in the FileStream, and then create Streamwrite
 classProgram {Static voidMain (string[] args) {FileStream Afile=NewFileStream (@"D:\YGTfiletest\streamwriter.txt", FileMode.OpenOrCreate); StreamWriter SW=NewStreamWriter (Afile); Sw. WriteLine ("Swap Lines");//the WriteLine () method writes a string that is handed to it, followed by a swap lineSw. WriteLine ("Swap Lines"); Sw. Write ("does not replace the line");//The write () method simply writes the string sent to him in the file without appending a line breakSw. Write ("does not replace the line"); Sw.        Close (); }    }

C # Language---File read-write operations

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.