Absrtact: Learning C # has been a process, review the previous code and notes, do some common summary, I hope that in the future work if used, convenient to find. Of course, the primary purpose of the individual is to deepen the impression at the same time, you can practice typing speed. Hope also persist. Of course, it would be better if there was a little bit of help for other people.
This article covers the following:
1, commonly used for string Operations 2, set 3, file operations
1, commonly used for string manipulation:
A, string interception (Substring):
string " I love the People's Republic " = str. Substring (24); // parameter 1: Starting the intercepted index (starting from 0) parameter 2: Length of intercept
b, the string begins with what, and ends with what:
Str. StartsWith (" i "); Str. EndsWith (" State "); // returns TRUE or false
C, String segmentation: More commonly used, the string is divided, often for the operation of a string into a string array, according to the character of the string, select the desired part.
stringServerdata ="OK: Operation successful"; string[] data = Serverdata.split (':'); //string[] data = Serverdata.split (new char[] {': '}, Stringsplitoptions.removeemptyentries); //this way, you can add more strings that need to be truncated in a char array for(inti =0; I < data. Length; i++) {Console.WriteLine (data[i]); } //The result is: OK and operation succeeded
D. Compare two strings for consistency and ignore case (Equals: Parameter 2 can choose multiple comparisons, Common: compare two object
string str1=abc; string str2 = AbC; bool b = str1. Equals (str2, stringcomparison.ordinalignorecase); // The result is: true
E, string array insert operation: Join
string " Zhang San " " John Doe " " Harry " stringstring. Join ("| ", str); // The output is: Zhang San | John Doe | Harry insert into the middle of each array element
Summary: String also has a lot of operations, the use of high frequency on the above, of course, some of the use of C # can be point out and then read the text instructions to use
2: Collection
A collection is a very common thing. Common collections are: a set of key-value pairs, a generic collection
ArrayList (Collection): Can add data
Hashtable (set of key-value pairs): The key value can be any form of data type
Dictionary key-value pairs collection (common):
dictionary<intstringnew dictionary<intstring> (); // The key must be of type int and the value must be a string type dic. ADD (1" Zhang San "); // Add Data dic. Remove (1); // It comes in the key-label DIC. Clear (); // emptying the collection
List generic collection (Common):
List <int> list=Newlist<int> ();//StatementList. ADD (1);//Add DataList. AddRange (New int[] {3,4,5,6,7,8,9});//Add CollectionList. RemoveAt (2);//index subscript starting from 0List. RemoveRange (2,4);//Remove 4 elements starting at index 2List. Clear ();//emptying the collection
Collections are more commonly used and are relatively simple to use. There are many commonly used, such as: Contains (whether included) FirstOrDefault: the first element,. ToArray: Convert an array, etc. can list then point out, and then according to the instructions
3. File operation
Summary: File operations are essential in some projects, to some of the path of uploading pictures, to write some documents, log files to save the like
A: Path class that specializes in manipulating paths: (Static Class)
usingSystem.IO;stringstr =@"C:\Program Files (x86) \iis\microsoft Web Deploy v3\es\c#.txt"; Path.getfilename (str); //Get file namePath.getfilenamewithoutextension (str);//file name with no extensionPath.getextension (str);//get file name extensionPath.GetFullPath (str);//get file absolute pathPath.Combine (@"c:\a\b\c\",@"F\.avi");//merge the two pathsPath.getdirectoryname (str);//Get path name, no file name
Path is used in relation to paths, sometimes mixed with file, may be a personal reason
B:file Read and write data
(1): Read in bytes:
byte [] Bte = file.readallbytes (@ "C:\Users\xsh.cs\Desktop\new.txt"); string str = Encoding.Default.GetString (BTE); // Convert to string (most applicable) also: UTF8Encoding.Default.GetString (BTE), encoding.getencoding ("GB2312"). GetString (BTE)
, ASCIIEncoding.Default.GetString (BTE) and many other encoding formats
(2): Read row by line
string [] st = File.ReadAllLines (@ "C:\Users\Administrator\Desktop\new.txt", Encoding.default); // line-by-row read content traversal array to operate on each row
(3): Read in text form
string str = file.readalltext (@ "C:\Users\Administrator\Desktop\new.txt", Encoding.default); // read as text is not suitable for other classes such as Picture class, video file class, etc.
(a): Write Data in byte form
byte [] by = Encoding.Default.GetBytes (str); File.writeallbytes (@ "C:\Users\Path\new.txt", by);
(b): Write data row by line in the form of an array
File.writealllines ("new.txt", Strarray); // Strarray for the defined array
(c): Overall write
File.writealltext ("new.txt", str); // overall write, the most common way str is a string
(d): Additional
File.appendalltext ("new.txt", str); File.appendalllines ("new.txt", str); // row by line append
C:filestream file stream
(1): Read file:
using(FileStream fread=NewFileStream (@"C:\Users\path.txt", FileMode.OpenOrCreate, FileAccess.Read)) { byte[] buffer =New byte[1024x768*1024x768*2]; intR = fread. Read (Buffer,0, buffer. Length);//returns the number of valid bytes currently read stringstr = Encoding.Default.GetString (buffer,0, R);//decoding} //parameter ①: Write file path for which file//parameter ②: What to do with this file//parameter ③: What to do with the data for this file
(2): Write file:
using New FileStream (@ "C:\Users\ file stream. txt", FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = Encoding.Default.GetBytes (str); // Str is a string 0 , buffer. Length); }
(3): Copy files:
stringPath =@"C:\Users\video.avi"; stringNewPath =@"C:\Users\videoNew.avi"; //Create a file stream that is responsible for reading using(FileStream fread =NewFileStream (Path, FileMode.OpenOrCreate, FileAccess.Read)) { //Create a file stream to write to a file using(FileStream fwrite =NewFileStream (NewPath, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer =New byte[1024x768*1024x768*5]; while(true)//file is too large, may be read and written at one time, need to loop { intR = fread. Read (Buffer,0, buffer. Length); if(r = =0)//when a byte is not read, the description is complete, and the loop jumps out { Break; } Elsefwrite. Write (Buffer,0, R); }} Console.WriteLine ("Copy succeeded! "); }
Why use using? When a class eventually inherits the IDisposable interface, it is necessary to release the resource space, and use it to automatically free up resource space, improve efficiency and reduce the amount of code.
D:streamreader and StreamWriter
//Readusing(StreamReader sread =NewStreamReader (@"C:\Users\Path.txt", Encoding.default)) { while(!sread.endofstream)//indicates whether the position of the current stream is the end{Console.WriteLine (Sread.readline ()); } }//Write using(StreamWriter STWR =NewStreamWriter (@"C:\Users\Path.txt",true, Encoding.default)) {STWR. Write (str);}
Summary: Two ways can be read and write to the file, relative stream with a little more, the usage is very simple, according to write or Read method, the corresponding parameters can be passed.
Summary:C # has a large part of the basic syntax, the most important is to use some of the Microsoft package of classes, some methods. Look at the overloads of the methods of these classes. If you have those language packs for VS, you can see what each method overload does and then use it accordingly. Pass in the appropriate parameters to see the return value.
C # Basics (1)