C # Essentials Supplement

Source: Internet
Author: User

1 Cross-transfer of strings to time

Datetime.tryparse an empty string, is null, or is malformed, the value represented by the converted datetime is: 0001/1/1 0:00:00, this is the value of Datetime.minvalue.

use public static DateTime ParseExact (string s, string format, IFormatProvider provider), instance method conversion time, you can specify the format of the conversion. Where format is the input character S. If the specified format is not the same as the input character format, an exception is thrown

For example:

DateTime = "2017-11-18 17:25:53"; Throws an exception, this type corresponds to the format: Yyyy-mm-dd HH:mm:ss

String dateTime = "20171118172553";

IFormatProvider Yyyymmddformat = new CultureInfo (String.Empty, false);

DateTime time = DateTime.ParseExact (datetime, "YYYYMMDDHHMMSS", Yyyymmddformat);

2 comparison time successively

Use the public int CompareTo datetime (datetime value); instance method.

Example:

String dateTime = "2017-11-28 12:57:30";

DateTime DT;

Datetime.tryparse (DateTime, out DT);

int cr = Dt.compareto (DateTime.Now);

If the CR is greater than 0,dt time later than (current time) DateTime.Now, the integer value of the time is greater than the integer value of DateTime.Now.

if the CR equals 0,dt time equals (current time) DateTime.Now, that is, the integer value of the time equals the integer value of DateTime.Now.

If the CR is less than 0,DT time before (the current time) DateTime.Now, the integer value of the time is less than the integer value of DateTime.Now.

3 StreamWriter

Pass the directory where the file is located the StreamWriter constructor, instead of passing the full path of the file, throws the following exception, which appears to have no access to the file directory, in fact it is wrong to pass the file directory to the StreamWriter constructor.

4 writing data in Sream to a file

The wrong procedure one:

gets the length of the stream and then transforms to int, which is prone to truncation of data, resulting in the failure to read the entire contents of the stream.

//Read          LongLength =0; using(Stream fs =NewFileStream ("d:\\ command-line installation Mysql.docx", FileMode.Open)) {Length=FS.            Length; }            byte[] bytes =New byte[length]; using(Stream fs =NewFileStream ("d:\\ command-line installation Mysql.docx", FileMode.Open)) {                intCountin = fs. Read (Bytes,0, (int) length); }//Write            using(Stream fs =NewFileStream ("d:\\ command-line installation Mysqlnew.docx", FileMode.OpenOrCreate)) {fs. Write (Bytes,0, (int) length); }

Error procedure two:

It seems that the error type one does not occur, but there is still data truncation. Call FileStream 's Read instance method:read (byte[] buffer, int offset, int count),offset This parameter is of type int , the Numbytesread is transformed to int, and once the offset exceeds this value, a portion of the data read is duplicated.

/Read           using(Stream fs =NewFileStream ("d:\\ command-line installation Mysql.docx", FileMode.Open)) {                intc =10000; LongNumbytesread =0; LongNumbytestoread =FS.                Length;  while(numbytestoread>0)                {                    if(FS. Length-numbytesread <=c) {c= (int) (FS. Length-numbytesread); }                    intn = fs. Read (Bytes, (int) Numbytesread, c); Numbytesread+=N; Numbytestoread-=N; }}//Write            using(Stream fs =NewFileStream ("d:\\ command-line installation Mysqlnew.docx", FileMode.OpenOrCreate)) {fs. Write (Bytes,0, (int) length); }

Right procedure one:

ensure that the source data length in the above error practices does not exceed the maximum value of Int32. You can also use the following method, but also ensure that the source data length does not exceed the maximum value of int32:

//Read          using(Stream fs =NewFileStream ("d:\\ command-line installation Mysql.docx", FileMode.Open)) {                                intc =10000; LongPosition =0;  while(true) {Position=FS.                    Seek (position, seekorigin.begin); if(Position = =FS. Length) { Break; }                    if(Position + C >FS. Length) {C= (int) (FS. Length-position); }                    intn = fs. Read (Bytes, (int) position, c); Position+=N; }}//Write            using(Stream fs =NewFileStream ("d:\\ command-line installation Mysqlnew.docx", FileMode.OpenOrCreate)) {fs. Write (Bytes,0, (int) length); }

The right procedure two:

Use CopyTo (Stream destination)

CopyTo (Stream destination, int buffersize)

using the first method, the default buffer size is 4096, now look at the source fragment:

 Public void CopyTo (Stream destination)        {            ......             Internalcopyto (destination, _defaultcopybuffersize);        }

The Internalcopyto method is called in the CopyTo method to see the source fragment of the Internalcopyto method:

    private  voidint  buffersize)        {            ......                         byte New byte [buffersize];             int read;              while 0 0 )                0, read);        }

the Internalcopyto method calls the read method internally, and look at the source fragment of the Read method:

however in Stream there is no specific implementation of the Read method in this class, there is only one abstract method:

public abstract int Read ([in, out] byte[] buffer, int offset, int count);

As you can see from here , The function of the parameter buffersize in the CopyTo method is to set the size of the memory buffer, to read the data of length buffersize each time from the stream, put in the buffer, and then write to the target stream, repeating the process until all the streams have been copied. the larger the buffersize is, the more efficient it is to set the memory.

        usingnew FileStream ("d:\\ command line installation mysql.docx", FileMode.Open))        {             usingnew FileStream ("d:\\ command line installation mysqlnew.docx"  , FileMode.OpenOrCreate))             {                 fs. CopyTo (FSS);             }        }

5 file read and write efficiency and the effect of object frequent switch

Write File Method One:

 Public Static voidW () { for(inti =0; I < +; i++ )             {                 strings ="Sdfrgyjefgyhjdsfdfgfghgew"+i; using(StreamWriter SW =NewStreamWriter (@"D:\g.txt",true) ) {SW.                 Write (s); }             }         }

Way two:

 Public Static voidWT () {using(StreamWriter SW =NewStreamWriter (@"D:\gT.txt",true))             {                  for(inti =0; I < +; i++)                 {                     strings ="Sdfrgyjefgyhjdsfdfgfghgew"+i; Sw.                 Write (s); }             }         }

Analysis:

the way one writes every time the file, switches once StreamWriter object, and mode two writes all the strings to the file before closing the StreamWriter instance. The statistical data are as follows:

Number of Cycles

Way One

Way Two

1 million

21861ms

260ms

1000

231ms

13ms

C # Essentials Supplement

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.