C#_ file read and write common class introduction

Source: Internet
Author: User
Tags file copy

First, be familiar with. NET to manipulate files and folders.File class andThe directory class is the most important of the two classes. Understanding them will provide a great convenience for the implementation of the later features.
  This section first relates the file system to the two. NET class for a brief introduction.
   System.IO.File class andThe System.IO.FileInfo class primarily provides various operations on files that need to be referenced when usedThe System.IO namespace. The main properties and methods are described below through a program instance.
   (1)File Open method:File.Open ()
The declaration of this method is as follows:
public static FileStream Open (string path,filemode mode)
The following code opens the store in theThe C:/tempuploads directory name is calledNewFile.txt file, and write to the file in theHello
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 declaration of this method is as follows:
public static FileStream Create (string path;)
The following code shows how toC:/tempuploads under Create a name ofThe NewFile.txt file.
BecauseThe File.create method grants all users full read of the new file by default/write access, so the file is read/write access is open and must be closed before it can be opened by another application. To do so, you need to useof the FileStream classThe Close method closes the file that is created.
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 shows how to removeUnder the C:/tempuploads directoryNewFile.txt file.
private void DeleteFile ()
{
  File.delete (@ "C:/tempuploads/newfile.txt");
}
   (4)File Copy method:File.Copy

The method is declared as follows:

public static void Copy (string sourcefilename,string destfilename,bool overwrite);
The following code willC:/tempuploads/newfile.txt Copy ToC:/tempuploads/backup.txt.
BecauseOf the Cope methodThe overwrite parameter is set toTrue, so ifIf the BackUp.txt file already exists, it will be overwritten by the copy of the previous file.
private void CopyFile ()
{
  File.Copy (@ "C:/tempuploads/newfile.txt", @ "C:/tempuploads/backup.txt", true);
}
   (5)File Move Method:File.move
The method is declared as follows:
public static void Move (String sourcefilename,string destfilename);
The following code can add theC:/tempuploads under theBackUp.txt file moves toC Packing directory.
Attention:
Files can only be transferred under the same logical disk. If you try toThe files under C drive are transferred toD drive, error will occur.
private void MoveFile ()
{
  File.move (@ "C:/tempuploads/backup.txt", @ "C:/backup.txt");
}
  (6)To set the file properties method:File.setattributes
The method is declared as follows:
public static void SetAttributes (String path,fileattributes fileattributes);
The following code can set the fileThe properties of the C:/tempuploads/newfile.txt are read-only and hidden.
private void Setfile ()
{
  File.setattributes (@ "C:/tempuploads/newfile.txt",
  fileattributes.readonly| Fileattributes.hidden);
}
Files in addition to the common read-only and hidden properties, there areArchive (File archive status),System (Systems file),Temporary (temporary filesuch as For more information about file attributes, seeIn MSDNDescription of the fileattributes.
   (7)Methods to determine if a file exists:File.exist
The method is declared as follows:
public static bool Exists (string path);
The following code determines whether there is aC:/tempuploads/newfile.txt file. If present, copy the file first, then delete it, then move the copied file, if it does not exist, create the file first, then open the file and write, and finally set the file property to read-only and hidden.
if (File.exists (@ "C:/tempuploads/newfile.txt"))//Determine if the file exists
{
  CopyFile (); Copying files
  DeleteFile (); deleting files
  MoveFile (); Moving files
}
Else
{
  MakeFile (); Generating files
  OpenFile (); Open File
  Setfile (); Setting file properties
}
In additionThe file class is forText texts provide more support.
   · AppendText: Append text to an existing file
   · CreateText: Create or open a new file for writing text
   · OpenText: Open an existing text file for reading
But the above methods mainlyUTF-8 encoded text, which is not flexible enough. It is recommended that readers use the following code toTXT file for operation.
   ·RightTXT file for"Read"Operation, 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 ();
   ·RightTXT file for"Write"Operation, the sample code is as follows:
StreamWriter = new Streamwrite (@ "C:/tempuploads/newfile.txt", System.Text.Encoding.Default);
String filecontent;
Txtwriter.write (filecontent);
Txtwriter.close ();
   System.IO.Directory class andSystem.directoryinfo class
Mainly provides a variety of operations on the directory, using the need to referenceThe System.IO namespace. The main properties and methods are described below through a program instance.
   (1)Directory Creation Method:Directory.CreateDirectory
The method is declared as follows:
public static DirectoryInfo CreateDirectory (string path);
The following code demonstrates theUnder the C:/tempuploads folder, create a file namedThe NewDirectory directory.
private void Makedirectory ()
{
  Directory.CreateDirectory (@ "C:/tempuploads/newdirectoty");
}
   (2)Directory property setting Method:Directoryinfo.atttributes
The following code setsThe C:/tempuploads/newdirectory directory is read-only and hidden. As with file properties, directory properties are also usedFileAttributes to be set.
private void Setdirectory ()
{
  DirectoryInfo newdirinfo = new DirectoryInfo (@ "C:/tempuploads/newdirectoty");
  Newdirinfo.atttributes = fileattributes.readonly| Fileattributes.hidden;
}
   (3)Directory deletion method:Directory.delete
The method is declared as follows:
public static void Delete (string path,bool recursive);
The following code can add theC:/tempuploads/backup directory removal.The second parameter of the Delete method isBOOL type, which can decide whether to delete a non-empty directory. If the value of this parameter isTrue to delete the entire directory, even if there are files or subdirectories under that directory;False, it is only possible to delete the directory if it is empty.
private void DeleteDirectory ()
{
  Directory.delete (@ "C:/tempuploads/backup", true);
}
   (4)Directory Move Method:Directory.move
The method is declared as follows:
public static void Move (String sourcedirname,string destdirname);
The following code adds the directoryC:/tempuploads/newdirectory move toC:/tempuploads/backup.
private void MoveDirectory ()
{
  File.move (@ "c:/tempuploads/newdirectory", @ "C:/tempuploads/backup");
}
   (5)Gets all subdirectories methods under the current directory:Directory.getdirectories
The method is declared as follows:
public static string[] GetDirectories (string path;);
The following code readsc:/tempuploads/all subdirectories under the directory and store them in a string array.
private void Getdirectory ()
{
  string [] Directorys;
  Directorys = Directory. GetDirectories (@ "c:/tempuploads");
}
   (6)Gets all the file methods under the current directory:Directory.GetFiles
The method is declared as follows:
public static string[] GetFiles (string path;);
The following code readsC:/tempuploads/all the files in the directory and store them in a string array.
private void GetFile ()
{
  string [] Files;
  Files = Directory. GetFiles (@ "C:/tempuploads",);
}
   (7)Determine if a directory exists by:Directory.exist
The method is declared as follows:
public static bool Exists (
  string path;
);
The following code determines whether there is aC:/tempuploads/newdirectory directory. If present, get the subdirectories and files under the directory, then move them, and finally delete the moved directory. If it does not exist, the directory is created first, and then set the Directory property to read-only, hidden
if (File.exists (@ "c:/tempuploads/newdirectory"))Determine if a directory exists
{
  Getdirectory ();Get subdirectories
  GetFile ();Get file
  MoveDirectory ();Move Directory
  DeleteDirectory ();Delete Directory
}
Else
{
  Makedirectory ();Build Directory
  Setdirectory ();Set directory Properties
} 
Note:   The
Path has 3 ways, relative paths under the current directory, relative paths to the current work disk, absolute paths. Take c:/tmp/book as an example c:/tmp). "book", "/tmp/book", "C:/tmp/book" are c:/tmp/book.  
In addition, c#   "/" is a special character, you need to use c# language provides @ to simplify it. Simply add @ to the string and use c# should be expressed as "book", @ "/tmp/book", @ "C:/tmp/book".

C#_ file read and write common class introduction

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.