C # File Operations Gallery

Source: Internet
Author: User
Tags create directory datetime readline
C # File operation: C # append file StreamWriter sw = File.appendtext (Server.MapPath (".")   
+ "\\myText.txt"); Sw.   
WriteLine ("Chasing the ideal"); Sw.   
WriteLine ("kzlll"); Sw. WriteLine (".   
NET Notes "); Sw.   
Flush (); Sw.   
Close ();   
C # File operation: C # Copy file string orignfile,newfile; Orignfile = Server.MapPath (".")   
+ "\\myText.txt"; NewFile = Server.MapPath (".")   
+ "\\myTextCopy.txt";   
File.Copy (orignfile,newfile,true); C # File operation: C # Delete file string delfile = Server.MapPath (".")   
+ "\\myTextCopy.txt";   
File.delete (Delfile);   
C # File operation: C # move file string orignfile,newfile; Orignfile = Server.MapPath (".")   
+ "\\myText.txt"; NewFile = Server.MapPath (".")   
+ "\\myTextCopy.txt";   
File.move (Orignfile,newfile);   
C # File operations: C # Create directory//create directory C:\sixAge DirectoryInfo d= directory.createdirectory ("C:\\sixage");   
D1 points to C:\sixAge\sixAge1 DirectoryInfo d1= d.createsubdirectory ("SixAge1"); D2 points to c:\sixAge\sixAge1\sixAge1_1 DirectoryInfo d2= D1.   
Createsubdirectory ("Sixage1_1"); Set the current directory to C:\sixAge Directory.setcurRentdirectory ("C:\\sixage");   
Create a directory C:\sixAge\sixAge2 directory.createdirectory ("SixAge2");  
Create a directory C:\sixAge\sixAge2\sixAge2_1 directory.createdirectory ("Sixage2\\sixage2_1"); Recursively delete folders and files 〈% @PageLanguage =c#%〉〈% @Importnamespace = "System.IO"%〉〈scriptrunat=server〉publicvoiddeletefolder (Strin  
Gdir) {if (directory.exists (dir))//If there is a deletion of this folder {foreach (stringdindirectory).  
GetFileSystemEntries (dir)) {if (file.exists (d)) File.delete (d);//delete directly from file else DeleteFolder (d);//recursively Delete subfolders}  
Directory.delete (dir);//Delete empty folder Response.Write (dir+ "folder deletion succeeded"); Else Response.Write (dir+ "This folder does not exist");//If the folder does not exist prompt} protectedvoidpage_load (Object Sender,eventargse) {St  
Ringdir= "D:\\gbook\\11"; DeleteFolder (Dir);//Call Function Delete folder}//========================================//Implement a static method copy all content under the specified folder to the target folder  
Face////If the destination folder is read-only, an error will be. April18april2005instu//======================================== Publicstaticvoidcopydir (STRINGSRCPath, Stringaimpath) {try {//Check whether the destination directory ends with a directory split character if not, add if (aimpath[aimpath.length-1]!= Path.directoryse  
Paratorchar) Aimpath+=path.directoryseparatorchar; Determine if the target directory exists if it does not exist the new if (!  
Directory.Exists (Aimpath)) Directory.  
CreateDirectory (Aimpath); Get the list of files in the source directory, which is an array containing files and directory paths//If you point to the file below the copy destination file without the directory, use the following method//string[]filelist= Directory.GetFiles (src  
Path);  
string[]filelist= directory.getfilesystementries (Srcpath); Traverse all files and directories foreach (stringfileinfilelist) {//first as directory processing if present this directory is recursively copy the file if (directory.exists (file)) copy of the Directory  
Dir (file,aimpath+path.getfilename (file));  
Otherwise direct Copy file else File.Copy (file,aimpath+path.getfilename (file), true);  
} catch (Exceptione) {MessageBox.Show (e.tostring ());  
//========================================//Implementation of a static method to specify all content under the folder Detele//test should be handled carefully, after deletion can not be restored. April18april2005instu//======================================== Publicstaticvoiddeletedir (StringaimPath)  
{try {//Check whether the destination directory ends with a directory split character if not, add if (aimpath[aimpath.length-1]!= Path.directoryseparatorchar) aimpath+  
=path.directoryseparatorchar; Get the list of files in the source directory, which is an array containing files and directory paths//If you point to the file below the delete destination file without the directory, use the following method//string[]filelist= Directory.GetFiles (a  
Impath);  
string[]filelist= directory.getfilesystementries (Aimpath);  
Traverse all files and directories foreach (stringfileinfilelist) {//first as directory processing if there is this directory recursively delete the file if (directory.exists (file)) {  
Deletedir (aimpath+path.getfilename (file));  
//Otherwise direct Delete file else {file.delete (aimpath+path.getfilename (file));  
}///delete folder System.IO.Directory.Delete (aimpath,true);  
catch (Exceptione) {MessageBox.Show (e.tostring ());  
 
You need to reference the namespace: Usingsystem.io;  
/**////〈summary〉///copy folders (including subfolders) to the specified folder, both the source folder and the destination folder require an absolute path.  
Format: CopyFolder (source folder, target folder); 〈/summary〉///〈paramname= "Strfrompath" 〉〈/param〉///〈paramname= "Strtopath" 〉〈/param〉//------------------------- ---------------//author: Tomorrow go begging qq:305725744//----------------------------------------Publicstaticvoidcopyfolder (Stringstrfrompath, Stringstrtopath) {//If the source folder does not exist, create an if (!  
Directory.Exists (Strfrompath)) {directory.createdirectory (Strfrompath);  
//Get the folder name Stringstrfoldername=strfrompath.substring (Strfrompath.lastindexof ("\") +1,strfrompath to be copied.  
 
Length-strfrompath.lastindexof ("\")-1); If there is no source folder in the destination folder, create the source folder in the destination folder if (!  
Directory.Exists (strtopath+ "\" +strfoldername)) {directory.createdirectory (strtopath+ "\" +strFolderName);  
 
//Create an array to save the file name under the source folder String[]strfiles=directory.getfiles (Strfrompath);  
Cycle Copy file for (inti=0;i〈strfiles.length;i++) {//Get copy of file name, only filename, address truncated. Stringstrfilename=strfiles[i]. Substring (Strfiles[i]. LastIndexOf ("\") +1, Strfiles[i].  
Length-strfiles[i].  
LastIndexOf ("\")-1);  
Start copying files, true to overwrite files with the same name file.copy (strfiles[i],strtopath+ "\" +strfoldername+ "\" +strfilename,true); }//Create DirectoryInfo instance Directoryinfodirinfo=newdiRectoryinfo (Strfrompath);  
Gets the name of all subfolders under the source folder Directoryinfo[]zipath=dirinfo.getdirectories (); for (intj=0;j〈zipath.length;j++) {//Get all subfolder names stringstrzipath=strfrompath+ "\" + zipath[j].  
ToString ();  
Take the resulting subfolder as a new source folder, start a new round of copy copyfolder (strzipath,strtopath+ "\" + strfoldername); C # File actions: Reading text file **////〈summary〉//reading text file//〈/summary〉4private void Readfromtxtfile () 5{if (filepat  
H.postedfile.  
   FileName!= "") {Txtfilepath = FilePath.PostedFile.FileName;  
Fileextname = txtfilepath.substring (Txtfilepath. LastIndexOf (".")  
 
  +1,3);  
  if (fileextname!= "txt" && fileextname!= "txt") {Response.Write ("Please select a text file");  
  else {StreamReader FileStream = new StreamReader (Txtfilepath,encoding.default);  
  Txtcontent.text = Filestream.readtoend ();  
  Filestream.close (); The C # File action: Get file list **////〈summary〉//get file list//〈/summary〉private void Getfilelist () {string strcur DIr,filename,fileext;  
     
   /**////file size long FileSize;  
   /**////the last modification time;  
 
   DateTime filemodify; /**////Initialize if (!  
    IsPostBack) {/**////when initializing, the directory Strcurdir = Server.MapPath (".") where the current page is assumed to be the default;  
    Lblcurdir.text = Strcurdir;  
   Txtcurdir.text = Strcurdir;  
    else {strcurdir = Txtcurdir.text;  
    Txtcurdir.text = Strcurdir;  
   Lblcurdir.text = Strcurdir;  
   } FileInfo fi;  
   DirectoryInfo dir;  
   TableCell TD;  
   TableRow tr;  
     
   TR = new TableRow ();  
   /**////dynamically add cell content td = New TableCell (); Td.  
   Controls.Add (New LiteralControl ("filename")); Tr.  
   Cells.add (TD);  
   td = New TableCell (); Td.  
   Controls.Add (New LiteralControl ("file type")); Tr.  
   Cells.add (TD);  
   td = New TableCell (); Td.  
   Controls.Add (New LiteralControl ("File Size")); Tr.  
   Cells.add (TD);  
   td = New TableCell (); Td.  
   Controls.Add (New LiteralControl ("Last Modified Time")); Tr.  
 
   Cells.add (TD); Tabledirinfo.rows.ADD (TR);  
     
   /**////creates directory reference objects for the current directory DirectoryInfo dirinfo = new DirectoryInfo (txtcurdir.text);  
The/**////loop determines the files and directories in the current directory foreach (FileSystemInfo FSI in Dirinfo.  
     Getfilesysteminfos ()) {FileName = "";  
     Fileext = "";  
         
     FileSize = 0;  
             
     /**////if it is a file if (FSI is FileInfo) {fi = (FileInfo) FSI;
     /**////get the file? FileName = fi.  
             
    Name;
    /**////to get file extensions? Fileext = fi.  
             
   Extension; /**////gets the size of the file FileSize = fi.  
             
  Length; /**////gets the last modification time of the file Filemodify = fi.  
  LastWriteTime;  
             
    }/**////Otherwise be directory else {dir = (DirectoryInfo) FSI;
    /**////Get the catalogue? FileName = dir.  
             
    Name; /**////gets the last modification time of the directory filemodify = dir.  
             
    LastWriteTime;  
    The/**////settings file has the extension "folder" Fileext = "folder";  
       /**////dynamically add table content tr = new TableRow (); td = New TableCell (); 
       Td.  
       Controls.Add (FileName) (new LiteralControl); Tr.  
       Cells.add (TD);  
       td = New TableCell (); Td.  
       Controls.Add (New LiteralControl (Fileext)); Tr.  
       Cells.add (TD);  
       td = New TableCell (); Td.  
       Controls.Add (New LiteralControl (filesize.tostring () + "byte")); Tr.  
       Cells.add (TD);  
       td = New TableCell (); Td.  
       Controls.Add (New LiteralControl (filemodify.tostring ("Yyyy-mm-dd hh:mm:ss")); Tr.  
       Cells.add (TD);  
   TABLEDIRINFO.ROWS.ADD (TR);  
C # File action: Read log file **////〈summary〉//read log file//〈/summary〉private void Readlogfile () {/**////from specified directory to hit Open or create a form read the log file FileStream fs = new FileStream (Server.MapPath ("upedfile") + "\\logfile.txt", filemode.openorcreat  
 
   E, FileAccess.Read);  
     
   /**////defines the output string StringBuilder outputs = new StringBuilder (); /**////initializes the length of the string to output.  
     
   Length = 0;
   /**////create read data for the file stream created above? StreamReader read = new StreamReader (FS);
   /**////set the starting position of the current stream as the start of the file stream? Read.  
     
   Basestream.seek (0, Seekorigin.begin); /**////reads a file while (read. Peek () 〉-1) {/**////takes a row of the file and wraps output. Append (read.  
   ReadLine () + "\ n");
   /**////Close the release read data? Read.  
     
   Close (); /**////returns the contents of the log file read to return output.  
ToString (); C # File operation: Write log file **////〈summary〉//write log file//〈/summary〉//〈param name= "input" 〉〈/param〉private void Writelogf  
   Ile (String input) {/**////Specifies the directory string fname = Server.MapPath ("upedfile") + "\\logfile.txt" of the log file;  
 
   /**////definition file Information object FileInfo finfo = new FileInfo (fname); /**////determine if the file exists and is greater than 2K if (finfo). Exists && Finfo. length〉) {/**////deletes the file finfo.  
   Delete ();
  /**////Create a write-only file? using (FileStream fs = Finfo.
  Openwrite ()) {/**////Create write data based on the file flow created above?  
         
   StreamWriter w = new StreamWriter (FS); /**////sets the starting position of the write data stream to the end of the file stream W.basestream.seek (0, SeekOrigin.  
         
   End);  
         
  /**////writes "Log Entry:" W.write ("\nlog Entry:");  
/**////writes the current system time and wraps the line W.write ("{0} {1} \ r \ n", DateTime.Now.)  
         
   Tolongtimestring (), DateTime.Now.ToLongDateString ());  
         
   /**////writes the log content and wraps the line w.write (input + "\ n");  
         
 /**////writes to----------------"and wraps W.write ("------------------\ n ");
  /**////empty the contents of the buffer and write the buffer contents to the base?  
         
       W.flush ();
       /**////Write Data off?  
   W.close (); C # File actions: Create HTML file **////〈summary〉//create HTML file//〈/summary〉private void Createhtmlfile () {/**//  
   Defines an array with a consistent number of HTML tags string[] newcontent = new STRING[5];  
   StringBuilder strhtml = new StringBuilder ();  try {/**////Create StreamReader object using (StreamReader sr = new StreamReader (Server.MapPath ("createhtml")  
             
    + "\\template.html")) {String oneline; /**////reads the specified HTML file template while (Oneline = Sr. ReadLine ())!= null) {STRHTml.  
           Append (oneline); } Sr.  
       Close (); Exception Err {/**////Output exception information Response.Write (Err.  
   ToString ());
   /**////assign value to tag array newcontent[0] = txttitle.text;//?  
   NEWCONTENT[1] = "backcolor= ' #cccfff";//Background color newcontent[2] = "#ff0000";//Font color newcontent[3] = "100px";//font size NEWCONTENT[4] = txtcontent.text;//main content/**////generate HTML file try {/**////According to the new content above specifies the HTML file to be generated St  
         
  Ring fname = Server.MapPath ("createhtml") + "\" + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". html"; /**////replaces the markup in the HTML template file for the new content for (int i=0;i〈5;i++) {strhtml.  
   Replace ("$htmlkey [" +i+ "]", newcontent[i]);  
         
   /**////Create the file information object FileInfo finfo = new FileInfo (fname);
   /**////create a file in the form of open or write? using (FileStream fs = Finfo.
 Openwrite ()) {/**////Create write data based on the file flow created above?  
StreamWriter sw = new StreamWriter (Fs,system.  
     Text.Encoding.GetEncoding ("GB2312"));        
  /**////writes the new content to the HTML page created by the SW.  
  WriteLine (strhtml); Sw.  
  Flush (); Sw.  
  Close ();
 /**////set the genus of hyperlinks?  
 Hycreatefile.text = DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". html";  
   Hycreatefile.navigateurl = "createhtml/" +datetime.now.tostring ("YYYYMMDDHHMMSS") + ". html"; The catch (Exception err) {Response.Write (err.  
   ToString ());  }  
}

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.