C # File operations,

Source: Internet
Author: User

C # File operations,

FileClass is a static class, mainly used to provide some function libraries.The static objects class provides many static methods that support basic file operations, including creating, copying, moving, deleting, and opening a file.FileThe parameters of class methods are mostly paths.Path.FileSome methods can returnFileStreamAndStreamWriter. They can be used together.

The System. IO. File class and System. IO. FileInfo class provide various operations on files. The System. IO namespace must be referenced during use. The following describes the main attributes and methods of a program instance.


(1)File opening method:File. Open ()


The statement of this method is as follows:

Public static FileStream Open (string path, FileMode mode)
 

The following code opens the file named newfile.txt in the c: \ tempuploadsdirectory and writes hello to the file.
 

Private void OpenFile ()
{
FileStream. TextFile = File. Open (@ "c: \ tempuploads \ newFile.txt", FileMode. Append );
Byte [] Info = {(byte) 'h', (byte) 'E', (byte) 'l', (byte) 'l', (byte) 'o '};
TextFile. Write (Info, 0, Info. Length );
TextFile. Close ();
}


(2)File Creation method:File. Create ()


The statement of this method is as follows:

Public static FileStream Create (string path ;)
 

The following code demonstrates how to create a file named newfile.txt under c: \ tempuploads.
Because File. by default, the Create method grants all users full read/write access to the new file. Therefore, the file is opened with the read/write access permission, which must be disabled before it can be opened by other applications. Therefore, you must use the Close method of the FileStream class to Close the created file.
 

Private void MakeFile ()
{
FileStream NewText = File. Create (@ "c: \ tempuploads \ newFile.txt ");
NewText. Close ();
}


(3)File Deletion method:File. Delete ()


The method is declared as follows:
Public static void Delete (string path );


The following code deletes the newfile.txt file in the c: \ tempuploadsdirectory.
Private void DeleteFile ()
{
File. Delete (@ "c: \ tempuploads \ newFile.txt ");
}
 

(4)File Replication method:File. Copy

The method is declared as follows:

Public static void Copy (string sourceFileName, string destFileName, bool overwrite );


The following code copies c: \ tempuploads \ newFile.txt to c: \ tempuploads \ BackUp.txt.
The overwritegion of copetypes is set to true, so that if the backup.txt file already exists, it will be overwritten by the copied file.


Private void CopyFile ()
{
File. Copy (@ "c: \ tempuploads \ newFile.txt", @ "c: \ tempuploads \ BackUp.txt", true );
}


(5)File movement method:File. Move


The method is declared as follows:
Public static void Move (string sourceFileName, string destFileName );
 

The following code moves the backup.txt file under c: \ tempuploadsto the c root directory.


Note:
File Transfer can only be performed on the same logical disk. If you try to transfer files from drive C to drive D, an error will occur.
 

Private void MoveFile ()
{
File. Move (@ "c: \ tempuploads \ BackUp.txt", @ "c: \ BackUp.txt ");
}


(6)How to Set file attributes:File. SetAttributes
 

The method is declared as follows:
Public static void SetAttributes (string path, FileAttributes fileAttributes );


The following code sets the properties of file c: \ tempuploads \ newFile.txt to read-only and hidden.
 

Private void SetFile ()
{
File. SetAttributes (@ "c: \ tempuploads \ newFile.txt ",
FileAttributes. ReadOnly | FileAttributes. Hidden );
}


In addition to common read-only and hidden attributes, files include Archive, System, and Temporary. For details about file attributes, see the description of FileAttributes in MSDN.


(7)To determine whether a file exists:File. Exist
 

The method is declared as follows:
Public static bool Exists (string path );
 

The following code checks whether the c: \ tempuploads \ newFile.txt file exists. If the file exists, copy the file first, delete it, and then move the copied file. If the file does not exist, create the file first, open the file, and write the file, finally, set the file attribute to read-only and hidden.
 

If (File. Exists (@ "c: \ tempuploads \ newFile.txt") // checks whether the File Exists.
{
CopyFile (); // copy a file
DeleteFile (); // delete an object
MoveFile (); // move the file
}
Else
{
MakeFile (); // generate a file
OpenFile (); // open the file
SetFile (); // set file attributes
}


In addition, the File class provides more support for Text.


· AppendText: append text to an existing file.
· CreateText: Creates or opens a new file for writing text.
· OpenText: open an existing text file for reading.


But the above method mainly on the UTF-8 encoding text operations, which is not flexible enough. We recommend that you use the following code to operate the txt file.
· Read the txt file. The sample code is as follows:
 

StreamReader TxtReader = new StreamReader (@ "c: \ tempuploads \ newFile.txt", System. Text. Encoding. Default );
String FileContent;
FileContent = TxtReader. ReadEnd ();
TxtReader. Close ();


· Perform the "write" Operation on the txt file. The sample code is as follows:


StreamWriter = new StreamWrite (@ "c: \ tempuploads \ newFile.txt", System. Text. Encoding. Default );
String FileContent;
TxtWriter. Write (FileContent );
TxtWriter. Close ();
 

 


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

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.