such as Peng Web study notes (iv). NET Common class libraries

Source: Internet
Author: User
Tags file copy

. NET Common class libraries

A, string member method (common)
1,bool Contains (String str) determines whether a string object contains the given content

2,bool StartsWith (String str): Determines whether the string object starts with the given string.

3,bool EndsWith (String str): Determines whether the string object ends with the given string.

Case: Determine if it is a URL: begins with/HTTP, ends with. com or. cn.

Case: Determine whether the user entered the message is QQ mailbox, user input user name contains "Mao Ze East" and other sensitive words

4,int length Gets a string that is a long property

Str. Length

5,char ch = str[3];

6,int indexOf (int ch)//Returns the index of the first occurrence of the specified character in this string

7,int indexOf (String str)//Returns the index of the first occurrence of the specified string in this string

8,lastindexof//last seen position

9,string Substring (int start)//intercept string, returns the string that was intercepted at the beginning of the specified position

10,string substring (int start,int length)//intercept string, returns a string that intercepts the specified length from the specified position

11,string ToLower ()//turn the string into lowercase;

12,string ToUpper ()//turn the string into uppercase

13,string replace (char Oldchar,char Newchar)//replaces the specified old character with a new character;

14,string Replace (string lodstr,string newstr)//Replace the specified old string with a new string

15,string trim ()//remove spaces at both ends of the string,

16,trim (params char[] trimChars)//Remove the given character at both ends

17,trimend and Trimstrat//Remove the opening and closing spaces

18,string is immutable, so the above operation is to generate a new string object, to use the return value to receive the new string.

19,string[] Split ()//overloaded Many methods, the string is cut by the delimiter.

Case: Dividing a string with ","

Second, string static method

1,bool IsNullOrEmpty (String value)//Determines whether a string is null or an empty string

2,bool euqals (String a,string b,stringcomparison.ordinallgnorecase)//case-insensitive comparison of two strings

3,string Join (String separator,params string[] value)//To concatenate an array (collection) with a delimiter separator as a string

Third, StringBuilder

Because the string is immutable, a new string object is generated when the string is concatenated, resulting in a waste  

1,append ();
StringBuilder sb = new StringBuilder ();
Sb. Append (S1);
Sb. Append (S2). Append (S3);//Because the Append method returns the This object (the current object), you can chain-program

Finally, use string s = sb. ToString (), the concatenation result string can be generated once

2,appendline ();

Appends the default line terminator to the end of the current System.Text.StringBuilder object. (After the addition, enter)

Four, Nullable int

int is a value type and cannot be null. You can use int to represent "nullable int" in C #

Note the conversion of the type:

Int? i = 5;
if (i!=null)
{
int i1 = (int) i;//requires a strong turn
}
can also be through I. HasValue, the judgment is null, I.value gets the value of I

By IL, the int is actually translated to the nullable<int> type by the compiler.

V. Type of date

The DateTime class represents the time data type. is a struct and therefore a value type

DateTime.Now Current Time,

Datetime.today Current Date

You can get the year, month, and hour of the date through the attributes of years, months, and hour;
You can also use constructors to create an object at a given time

Vi. The concept of anomalies
The exception occurs when the program is not in normal condition. Exceptions are thrown in the form of an exception class object that describes the exception information, where it occurred, and so on.

The root class of the exception is exception. Exception classes are generally inherited from excrption

Seven, the abnormal capture

Try
{
String s = null;
S.tostring ();
}
catch (NullReferenceException ex)
{
Console.WriteLine ("Empty" +ex. Message);
}

An ex is an exception class object that has an exception, and the variable name is arbitrary if it does not conflict

In exception handling, once there is a problem in the try. Discard the code after the try code block, and jump directly into the catch execution.

If there is code behind the try code, the catch will continue to execute after it has been processed


Handling of eight or more exceptions
Try
{
int a = 10;
int b = 0;
Console.WriteLine (A/b);
Int[] arr = {A-i};
Console.WriteLine (Arr[3]);
}
catch (DivideByZeroException AE)
{
Console.WriteLine ("Divisor cannot be 0");
}
catch (IndexOutOfRangeException AE)
{
Console.WriteLine ("Array out-of-bounds exception");
}

You can catch a parent exception so that you can catch all of the subclass exceptions, but it's strongly not recommended, and there's no reason to catch exceptions


Nine, do not eat abnormal
catch (Exception ex)
{
Empty code
}

Do not just catch the exception to do nothing or just print it, this is not normal "exception handling"

Do not know how to deal with the catch, error than "Hide the mistake" good. This thought "will not go wrong", actually is the exception "eat", will let the program into chaos State

To handle the exception appropriately

Ten, finally

Try
{
There may be a problem with the code
}
catch (Exception type exception variable)
{
Processing mode
}
Finally
{
Code to execute, whether or not an exception occurs
}

Finally, the recovery of resources in general and so on.


Xi. File class

File is a static class (cannot be new), and its main static methods are:

1,void Delete file (string path)

2,bool Exists (string path) to determine if a file exists

3,string[] ReadAllLines (string path) reads the contents of a text file into a string array

4,string ReadAllText (string path) reads a text file as a string

5,void writealllines (String path,string[] contents) writes string[] to a file

6,void WriteAllText (String path,string contents) writes the string contents to the file path

7,appendalltext attaching content to a file

8,copy Copying files

9,move Moving files

12. Directory folder class, for static class

1,createdirectory (string path) to create a folder full path

2,void Delete (String Path,bool recursive)
Deleting a folder path,recursive Indicates whether the child files and subfolders are also deleted.
Throws an exception if the folder is not empty and recursive=false

Example code: Directory.delete (@ "full path", true);

3,boolexists (string path) to determine if a folder exists

4,directory.enumeratefiles (); Returns an enumerable collection of file names in the specified path.

5, Directory.enumeratedirectories (); Returns an enumerable collection of directory names in the specified path that match the search pattern.

13. Streaming Stream

The 1,file class provides a way to read and write a text file, but for a method that the large file cannot provide, it takes up too much memory and requires a "streaming" approach

2,. NET simplifies the IO operations (file, network, etc.) into stream model stream, which is an abstract class,

Network, file, encryption, etc. are different subclasses,

The most common subclasses are FileStream, MemoryStream, etc.

3, when using stream, although you can:
FileStream fs = new FileStream ();
However, Stream fs = new FileStream (); Better!

If the variable type provided by the use of the operation can be satisfied, as far as possible with the parent class, interface declaration variables, (embodies the idea of polymorphism),

4,filestream Writing Files

FileStream fs = new FileStream (@ "D:\1.txt", filemode.create);//Create a text file
byte[] bytes = Encoding.Default.GetBytes ("Hello like Peng Net");//Will "Hello like Peng Net" encoded into a byte array object
Fs. Write (bytes, 0, bytes. LENGTH);//Operations FS object to write
Fs. Close ();//Closed stream

The stream is written in byte (bytes), char is converted to Byte, an English char is converted to a byte (corresponding ASCII code), and a Chinese char is converted to two byte

The byte[] length of the string obtained by default, UTF8, UTF32, and so on is not the same, so the different types of encoding are stored differently on the computer.

What code to write with what code to read, otherwise there will be garbled problems.

Note: Do not write to the C drive, because Win7, Win8 default normal program does not have permission to read and write C disk

5,filestream Read

1,byte[] bytes = new Byte[4];
Each time you read multiple bytes of data, you cannot read one file at a time, or it is too memory-intensive because the array is memory-intensive.
This is called "buffer", set too small CPU and hard disk will be very busy, set too much memory will be very "brace"

2,while (len = fs. Read (bytes,0,bytes. Length)) >0 continues to read from the stream up to bytes length, so many bytes of data are copied into the bytes array.
The next time read is to start reading from the last last read, reading the Read method again and again to return the total number of bytes read this time (such as encountering the last read may be read dissatisfaction),
Once the return = 0, the reading is done.
The initial value that is not assigned is 0 because the array position that is not filled is 0.

3,string s = Encoding.Default.GetString (Bytes,0,len); Convert byte[] to the corresponding string, considering the situation where the bytes is not fully utilized

4, byte stream is not suitable for reading content contains text document, easy to cause data confusion (byte[] contains half of the Chinese characters).

I want to use the StreamReader in the back.

14. Closing of resources

1, in the above program is defective, if the write occurs when the exception, FS will not close, the other program will not be able to write to this file, will also occupy resources

2, the resource must be used to close, once close after the operation will be error

3, correct is the practice is placed in the using () {} inside




15, using

1, you can declare multiple resources

using (MyFile f1 = new MyFile ()) using (MyFile F2 = new MyFile ())
{

}

2,using is actually a compiler-simplified try: The finally action,

3,using is just try: Finally, if catch is required, catch is

4, note: The object that implements the IDisposable interface is exhausted, dispose of


16, copy file

1, complete the file copy with two FileStream mates:
Reads a portion of the content from the FileStream of the source file, and then writes to the FileStream of the destination file.

explains the code:
1,while (len = Instream.read (bytes,0,bytes. Length) >0)
reads and returns the length of the read to Len, and then determines the value of Len, synthesized for one sentence.      

2,outstream.write (bytes,0,len);
Each write is then written from the last position of the last write. Writes byte[] Array B to OutStream, the off code is offset from the current write position, and the general write 0,len represents how long to write. The
buffer is set to 50 first, and modified to 1M to realize the change of speed. Use the Stopwatch class for code timing.


2, encapsulating a copy method
encapsulates a function void copy (Stream instream,stream outstream,int buffersize) Used to copy the instream to OutStream, and the
buffer size is buffersize. To check the legitimacy of the parameter (NULL, buffersize is reasonable)


3,.net 4.0 after the Stream class provides a CopyTo method


4,reader, Writer (text content)

reading and writing text files directly with stream is cumbersome because of the need to consider file encoding, Chinese characters, and so on

StreamReader, StreamWriter is a class used to read and write streams (Characterstream), which helps to automatically handle troublesome problems


17, encoding

1, because of historical reasons, how to store Chinese characters in the computer with a variety of standards, the most common is GB2312 (national standards, the expression of Chinese characters),
GBK (GB2312 extension, can also express traditional characters, etc.), UTF-8 (International Standard), UTF-16, etc.

2,ansi represents the default encoding for the current operating system, and if it is Chinese windows, the default is GBK

3, what code to save with what code to read, it will not garbled

4, how to save with other code? Determined by the StreamWriter constructor: New StreamWriter (OutStream, Encoding.UTF8
What code did you use for preliminary judgment? Notepad opens Save As and you can see

5, the read encoding is determined by the StreamReader constructor

18. Generic Container list<t>

1, the array length is fixed,list<t> can dynamically delete content.

List<t> is generic, and you can specify what type of data to put at the time of declaration.

2, how to increase

list<int> list = new list<int> ();

List. ADD (1);

List. ADD (2);

List. AddRange (New int[]{1,2,3,4,5});

List. AddRange (LIST2);//Add another list

3, how to traverse

int[] Nums = list. ToArray ();//list generic collection can be converted to an array

list<string> liststr = new list<string> ();

string[] str = Liststr.toarray ();

19. Generic Dictionary dictionary<key,value>

1, how to increase
Dictionary<string,string> dict = new dictionary<string,string> ();
Dict. ADD ("Zs", "Zhang San");
Dict. ADD ("ls", "John Doe");
Dict. ADD ("ww", "Harry");

2, how to modify
dict["ls"] = "Xiao Zhao";
String s = dict["ww"];

3, determine if it contains
Dict. ContainsKey ();

20. foreach

1, in addition to using a for loop can be traversed, the implementation of the Ieumerable interface object can also use foreach to traverse

String[] STRs = {"ASDASD", "Qweqweq", "GDFG"};
foreach (string s in STRs)
{
Console.WriteLine (s);
}

2,list<t>, dictionary<k,v> and so on all implements the IEnumerable interface the object can traverse

Dictionary<string,object> dict = new dictionary<string,object> ();
dict["Rupeng"] = 888;
dict["sina"] = "hehe";
Dict["Baidu"] = true;
foreach (keyvaluepair<string,object> kv in dict)
{
Console.WriteLine (KV. key+ "=" +kv. Value);
}

such as Peng Web study notes (iv). NET Common class libraries

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.