C # BASICS (1 ),
Abstract: I have been learning c # For a while. I will review the code and notes I have made and make some common summaries. I hope it will be useful in my future work to facilitate searching. Of course, my primary goal is to deepen my impression and practice typing speed. I hope to stick to it. Of course, it would be better if it could help others.
Content of this article:
1. common string operations 2. Set 3. File Operations
1. common string operations:
A. String truncation (Substring ):
String str = "I love the People's Republic of China"; str = str. Substring (2, 4); // parameter 1: index to be intercepted (starting from 0) parameter 2: length to be intercepted
B. start and end of a string:
Str. StartsWith ("I"); str. EndsWith ("country"); // return true or false
C. string segmentation: it is commonly used to separate strings. It is often used to divide a string into a string array. Based on the characteristics of the string, select the desired part.
String serverData = "OK: operation successful"; string [] data = serverData. split (':'); // string [] data = serverData. split (new char [] {':'}, StringSplitOptions. removeEmptyEntries); // you can add the string to be truncated in the char array for (int I = 0; I <data. length; I ++) {Console. writeLine (data [I]);} // The result is OK and the operation is successful.
D. Compare the two strings and ignore the case sensitivity (Equals: parameter 2 can be used to compare multiple methods. Commonly Used: compare two objects
String str1 = abc; string str2 = abC; bool B = str1.Equals (str2, StringComparison. OrdinalIgnoreCase); // The result is true.
E. String Array insert operation: Join
String [] str = {"Zhang San", "Li Si", "Wang Wu"}; string str2 = string. join ("|", str); // The output result is Zhang San | Li Si | Wang Wu is inserted in the middle of each array element.
Summary: there are still many operations on the string. The usage frequency is relatively high. Of course, c # can be used by some users and then read the text instructions.
2: Set
Set is a very common thing. Common collections include: Key-value pair set and generic set
ArrayList (SET): You can add data.
Hashtable (set of key-value pairs): the key value can be of any form of Data Type
Dictionary key-value pair set (commonly used ):
Dictionary <int, string> dic = new Dictionary <int, string> (); // The involved key must be of the int type, and the value must be of the string type dic. add (1, "Zhang San"); // Add data dic. remove (1); // the key-marked dic is passed in. clear (); // Clear the set
List generic set (commonly used ):
List <int> list = new List <int> (); // Declare list. add (1); // Add a data list. addRange (new int [] {3, 4, 5, 6, 7, 8, 9}); // Add a set list. removeAt (2); // index subscript starts from 0 list. removeRange (2, 4); // removes the list of four elements from index 2. clear (); // Clear the set
Set is more common and easy to use. There are many commonly used elements, such as: Contains (include or not) FirstOrDefault: the first element,. ToArray: can be converted to an array and can be list and clicked out, and then according to the instructions
3. File Operations
Abstract: file operations are essential to some projects, such as path operations for uploading images, saving written documents and log files.
A: path class for specific operation paths: (static class)
Using System. IO; string str = @ "C: \ Program Files (x86) \ IIS \ Microsoft Web Deploy V3 \ es \ c0000.txt"; Path. getFileName (str); // get the file name Path. getFileNameWithoutExtension (str); // Path of the file without an extension. getExtension (str); // get the file extension Path. getFullPath (str); // obtain the absolute Path of the file. combine (@ "c: \ a \ B \ c \", @ "f \. avi "); // combine two paths with Path. getDirectoryName (str); // get the path name without a file name
Path is used when it involves a Path. Sometimes it is often mixed with File, which may be a personal reason.
B: File reads and writes data.
(1): read in byte format:
Byte [] bte = File. readAllBytes (@ "C: \ Users \ xsh. cs \ Desktop \ new.txt "); string str = Encoding. default. getString (bte); // convert to a string (most suitable) and UTF8Encoding. default. getString (bte), Encoding. getEncoding ("GB2312 "). getString (bte)
, ASCIIEncoding. Default. GetString (bte) and Other encoding formats
(2): Read data row by row
String [] st = File. readAllLines (@ "C: \ Users \ Administrator \ Desktop \ new.txt", Encoding. default); // read the content row by row and traverse the array to operate on each row
(3): read in text format
String str = File. readAllText (@ "C: \ Users \ Administrator \ Desktop \ new.txt", Encoding. default); // reading in text format is not applicable to image, video, and other classes
(A): Write Data in bytes.
byte[] by = Encoding.Default.GetBytes(str);File.WriteAllBytes(@"C:\Users\Path\new.txt",by);
(B): Write Data row by row in the form of an array
File. WriteAllLines ("new.txt", strArray); // strArray is the defined array.
(C): overall write
File. WriteAllText ("new.txt", str); // write the entire data. The most common method is string.
(D): append
File. AppendAllText ("new.txt", str); File. AppendAllLines ("new.txt", str); // append row by row
C: FileStream file stream
(1): Read files:
Using (FileStream fread = new FileStream (@ "C: \ Users \ path.txt", FileMode. openOrCreate, FileAccess. read) {byte [] buffer = new byte [1024*1024*2]; int r = fread. read (buffer, 0, buffer. length); // returns the number of valid bytes currently read string str = Encoding. default. getString (buffer, 0, r); // decoding} // parameter ①: Specifies the file path for which a file is written. // parameter ②: operations on this file // parameter ③: operations on the file's data
(2): write files:
Using (FileStream fwrite = new FileStream (@ "C: \ Users \ file stream .txt", FileMode. openOrCreate, FileAccess. write) {byte [] buffer = Encoding. default. getBytes (str); // str is the string fwrite. write (buffer, 0, buffer. length );}
(3): copy a file:
String path = @ "C: \ Users \ video. avi "; string newpath = @" C: \ Users \ videoNew. avi "; // create a file stream using (FileStream fread = new FileStream (path, FileMode. openOrCreate, FileAccess. read) {// create a file stream using (FileStream fwrite = new FileStream (newpath, FileMode. openOrCreate, FileAccess. write) {byte [] buffer = new byte [1024*1024*5]; while (true) // The file is too large to be read or written at a time, loop {int r = fread. read (buffer, 0, buffer. length); if (r = 0) // when no Bytes are read, it indicates that the loop {break;} else fwrite is completed. write (buffer, 0, r) ;}} Console. writeLine ("Copied successfully! ");}
Why using? When a class finally inherits the IDisposable interface, it needs to release the resource space. With using, the resource space can be automatically released to improve efficiency and reduce the amount of code.
D: StreamReader and StreamWriter
// Read using (StreamReader sRead = new StreamReader (@ "C: \ Users \ Path.txt", Encoding. Default) {while (! SRead. endOfStream) // indicates whether the current stream is at the end {Console. writeLine (sRead. readLine () ;}}// write using (StreamWriter stwr = new StreamWriter (@ "C: \ Users \ Path.txt", true, Encoding. default) {stwr. write (str );}
Summary: You can perform read and write operations on files in either of the two methods. It is a little more useful than Stream. It is easy to use. You can pass in the relevant parameters according to the write or read methods.
Summary:C # has a large part of the basic syntax. The most important thing is to use some classes and Methods encapsulated by Microsoft. Reload the methods of these classes. If you have the vs language packs, you can view what each method overload is and use them accordingly. Input the required parameters to view the returned values.