C # file and folder operations

Source: Internet
Author: User

This article collects the most common methods for Operating Files in C # classic. The specific content is as follows: C # append, copy, delete, move a file, create a directory, recursively delete a folder and a file, copy all the content in a specified folder to the target folder, and Detele and, reading text files, obtaining file lists, reading log files, writing log files, creating HTML files, and using the CreateDirectory Method
C # append an object
StreamWriter sw = File. AppendText (Server. MapPath (".") + "\ myText.txt ");
Sw. WriteLine ("Chasing ideals ");
Sw. WriteLine ("kzlll ");
Sw. WriteLine (". NET notes ");
Sw. Flush ();
Sw. Close ();
C # copy an object
String OrignFile, NewFile;
OrignFile = Server. MapPath (".") + "\ myText.txt ";
NewFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Copy (OrignFile, NewFile, true );
C # delete an object
String delFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Delete (delFile );
C # Move files
String OrignFile, NewFile;
OrignFile = Server. MapPath (".") + "\ myText.txt ";
NewFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Move (OrignFile, NewFile );
C # create a directory
// Create the 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 the directory c: \ sixAge \ sixAge2
Directory. CreateDirectory ("sixAge2 ");
// Create the directory c: \ sixAge \ sixAge2 \ sixAge2_1
Directory. CreateDirectory ("sixAge2 \ sixAge2_1 ");
Recursively delete folders and files
<% @ Page Language = C # %>
<% @ Import namespace = "System. IO" %>
<Script _ runat = server>
Public void DeleteFolder (string dir)
{
If (Directory. Exists (dir) // if this folder Exists, delete it
{
Foreach (string d in Directory. GetFileSystemEntries (dir ))
{
If (File. Exists (d ))
File. Delete (d); // Delete the File directly.
Else
DeleteFolder (d); // recursively Delete subfolders
}
Directory. Delete (dir); // Delete an empty folder
Response. Write (dir + "folder deleted successfully ");
}
Else
Response. Write (dir + "this folder does not exist"); // If the folder does not exist, a prompt is displayed.
}
Protected void Page_Load (Object sender, EventArgs e)
{
String Dir = "D :\\ gbook \ 11 ";
DeleteFolder (Dir); // call the function to delete a folder
}

// ================================================ ======================
// Implement a static method to copy all the content in the specified folder to the target folder
// If the target folder is read-only, an error is returned.
// April 18April2005 In STU
// ================================================ ======================
Public static void CopyDir (string srcPath, string aimPath)
{
Try
{
// Check whether the target directory ends with a directory delimiter. If not, add it.
If (aimPath [aimPath. Length-1]! = Path. DirectorySeparatorChar)
AimPath + = Path. DirectorySeparatorChar;
// Determine whether the target directory exists. If it does not exist, create it.
If (! Directory. Exists (aimPath) Directory. CreateDirectory (aimPath );
// Obtain the file list of the source Directory, which is an array containing the file and directory path
// Use the following method if you direct to the file under the copy target file without including the Directory
// String [] fileList = Directory. GetFiles (srcPath );
String [] fileList = Directory. GetFileSystemEntries (srcPath );
// Traverse all files and directories
Foreach (string file in fileList)
{
// Process the file as a directory first. If this directory exists, recursively Copy the file under this directory.
If (Directory. Exists (file ))
CopyDir (file, aimPath + Path. GetFileName (file ));
// Otherwise, Copy the file directly.
Else
File. Copy (file, aimPath + Path. GetFileName (file), true );
}
}
Catch (Exception e)
{
MessageBox. Show (e. ToString ());
}
}
// ================================================ ======================
// Implement a static method to Detele all content in the specified folder
// Perform the test with caution. The operation cannot be restored after deletion.
// ================================================ ======================
Public static void DeleteDir (string aimPath)
{
Try
{
// Check whether the target directory ends with a directory delimiter. If not, add it.
If (aimPath [aimPath. Length-1]! = Path. DirectorySeparatorChar)
AimPath + = Path. DirectorySeparatorChar;
// Obtain the file list of the source Directory, which is an array containing the file and directory path
// Use the following method if you direct to the file under the Delete target file without including the Directory
// String [] fileList = Directory. GetFiles (aimPath );
String [] fileList = Directory. GetFileSystemEntries (aimPath );
// Traverse all files and directories
Foreach (string file in fileList)
{
// Process the file as a directory first. If this directory exists, recursively Delete the files under this directory.
If (Directory. Exists (file ))
{
DeleteDir (aimPath + Path. GetFileName (file ));
}
// Otherwise, Delete the file directly.
Else
{
File. Delete (aimPath + Path. GetFileName (file ));
}
}
// Delete a folder
System. IO. Directory. Delete (aimPath, true );
}
Catch (Exception e)
{
MessageBox. Show (e. ToString ());
}
}
Namespace to be referenced:
Using System. IO;
/** // <Summary>

/// </Summary>
/// <Param> </param>
/// <Param> </param>
//--------------------------------------------------
//---------------------------------------------------
Public static void CopyFolder (string strFromPath, string strToPath)
{
// If the source folder does not exist, create
If (! Directory. Exists (strFromPath ))
{
Directory. CreateDirectory (strFromPath );
}
// Obtain the name of the folder to be copied
String strFolderName = strFromPath. Substring (strFromPath. LastIndexOf ("\") + 1, strFromPath. Length-strFromPath. LastIndexOf ("\")-1 );
// If no source folder exists in the target folder, create the source folder in the target folder.
If (! Directory. Exists (strToPath + "\" + strFolderName ))
{
Directory. CreateDirectory (strToPath + "\" + strFolderName );
}
// Create an array to save the file name in the source folder
String [] strFiles = Directory. GetFiles (strFromPath );
// Copy objects cyclically
For (int I = 0; I <strFiles. Length; I ++)
{
// Get the copied file name. Only the file name is taken and the address is truncated.
String strFileName = strFiles [I]. substring (strFiles [I]. lastIndexOf ("\") + 1, strFiles [I]. length-strFiles [I]. lastIndexOf ("\")-1 );
// Start copying an object. true indicates overwriting an object of the same name.
File. Copy (strFiles [I], strToPath + "\" + strFolderName + "\" + strFileName, true );
}

// Create a DirectoryInfo instance
DirectoryInfo dirInfo = new DirectoryInfo (strFromPath );
// Obtain the names of all subfolders in the source folder
DirectoryInfo [] ZiPath = dirInfo. GetDirectories ();
For (int j = 0; j <ZiPath. Length; j ++)
{
// Obtain the names of all subfolders
String strZiPath = strFromPath + "\" + ZiPath [j]. ToString ();
// Use the obtained subfolder as the new source folder and start a new round of copying from the beginning
CopyFolder (strZiPath, strToPath + "\" + strFolderName );
}
}
1. Read text files
/** // <Summary>
/// Read a text file
/// </Summary>
Private void ReadFromTxtFile ()
{
If (filePath. PostedFile. FileName! = "")
{
TxtFilePath = filePath. PostedFile. FileName;
FileExtName = txtFilePath. Substring (txtFilePath. LastIndexOf (".") + 1, 3 );
 
If (fileExtName! = "Txt" & fileExtName! = "TXT ")
{
Response. Write ("select a text file ");
}
Else
{
StreamReader fileStream = new StreamReader (txtFilePath, Encoding. Default );
TxtContent. Text = fileStream. ReadToEnd ();
FileStream. Close ();
}
}
}
2. Get the file list
/** // <Summary>
/// Obtain the file list
/// </Summary>
Private void GetFileList ()
{
String strCurDir, FileName, FileExt;

/** // File Size
Long FileSize;

/** // The last modification time;
DateTime FileModify;

/** // Initialization
If (! IsPostBack)
{
/** // The default directory of the current page during initialization
StrCurDir = Server. MapPath (".");
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 ();

/** // Add cell content dynamically
Td = new TableCell ();
Td. Controls. Add (new LiteralControl ("file name "));
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 "));
Tr. Cells. Add (td );

TableDirInfo. Rows. Add (tr );

/*** // Create a directory reference object for the current directory
DirectoryInfo dirInfo = new DirectoryInfo (txtCurDir. Text );

/** // Cyclically determine the files and directories under 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 name
FileName = fi. Name;

/** // Obtain the file extension
FileExt = fi. Extension;

/** // Obtain the file size
FileSize = fi. Length;

/** // Get the last modification time of the file
FileModify = fi. LastWriteTime;
}

/** // Otherwise, it is a directory.
Else
{
Dir = (DirectoryInfo) fsi;

/** // Obtain the directory name
FileName = dir. Name;

/** // Obtain the last modification time of the Directory
FileModify = dir. LastWriteTime;

/** // Set the file extension to "folder"
FileExt = "folder ";
}

/** // Add Table content dynamically
Tr = new TableRow ();
Td = new TableCell ();
Td. Controls. Add (new LiteralControl (FileName ));
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 );
}
}
3. Read log files
/** // <Summary>
/// Read the log file
/// </Summary>
Private void ReadLogFile ()
{
/** // Read log files from the specified directory in the form of opening or creating
FileStream fs = new FileStream (Server. MapPath ("upedFile") + "\ logfile.txt", FileMode. OpenOrCreate, FileAccess. Read );

/** // Define the output string
StringBuilder output = new StringBuilder ();

/** // Initialize the string with a length of 0
Output. Length = 0;

/** // Create a read data stream for the file stream created above
StreamReader read = new StreamReader (fs );

/** // Set the starting position of the current stream to the starting point of the file stream.
Read. BaseStream. Seek (0, SeekOrigin. Begin );

/** // Read the file
While (read. Peek ()>-1)
{
/** // Get a line of content of the file and wrap the line
Output. Append (read. ReadLine () + "\ n ");
}

/** // Close and release the read data stream
Read. Close ();

/** // Return the log file content.
Return output. ToString ();
}
4. Write log files

/** // <Summary>
/// Write the log file
/// </Summary>
/// <Param> </param>
Private void WriteLogFile (string input)
{
/** // Specify the directory of the log file
String fname = Server. MapPath ("upedFile") + "\ logfile.txt ";
/** // Defines the object of File Information
FileInfo finfo = new FileInfo (fname );

/** // Determine whether the file exists and whether it is greater than 2 K
If (finfo. Exists & amp; finfo. Length & gt; 2048)
{
/** // Delete the object
Finfo. Delete ();
}
/** // Create a file-only stream
Using (FileStream fs = finfo. OpenWrite ())
{
/** // Create a write data stream based on the file stream created above
StreamWriter w = new StreamWriter (fs );

/** // Set the start position of the write data stream to the end of the file stream.
W. BaseStream. Seek (0, SeekOrigin. End );

W. Write ("\ nLog Entry :");

/** // Write the current system time and line feed
W. Write ("{0} {1} \ r \ n", DateTime. Now. ToLongTimeString (), DateTime. Now. ToLongDateString ());

/** // Write the log Content and line feed
W. Write (input + "\ n ");

/** // Write ---------------------------------------------- "and line feed
W. Write ("------------------------------------ \ n ");

/** // Clear the buffer content and write the buffer content to the base stream.
W. Flush ();

/** // Close the write data stream
W. Close ();
}
}
V. C # create an HTML file
/** // <Summary>
/// Create an HTML file
/// </Summary>
Private void CreateHtmlFile ()
{
/** // Defines an array with the same number of html tags
String [] newContent = new string [5];
StringBuilder strhtml = new StringBuilder ();
Try
{
/** // Create a StreamReader object
Using (StreamReader sr = new StreamReader (Server. MapPath ("createHTML") + "\ template.html "))
{
String oneline;

/** // Read the specified HTML file template
While (oneline = sr. ReadLine ())! = Null)
{
Strhtml. Append (oneline );
}
Sr. Close ();
}
}
Catch (Exception err)
{
/** // Output exception information
Response. Write (err. ToString ());
}
/** // Assign values to the marked Array
NewContent [0] = txtTitle. Text; // Title
NewContent [1] = "BackColor = '# cccfff'"; // background color
NewContent [2] = "# ff0000"; // font color
NewContent [3] = "100px"; // font size
NewContent [4] = txtContent. Text; // Main Content

/** // Generate an html file based on the new content above
Try
{
/** // Specify the HTML file to be generated
String fname = Server. MapPath ("createHTML") + "\" + DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";

/** // Replace the new content in the html Template File
For (int I = 0; I <5; I ++)
{
Strhtml. Replace ("$ htmlkey [" + I + "]", newContent [I]);
}
/** // Create a file information object
FileInfo finfo = new FileInfo (fname );

/** // Create a file stream in the form of opening or writing
Using (FileStream fs = finfo. OpenWrite ())
{
/** // Create a write data stream based on the file stream created above
StreamWriter sw = new StreamWriter (fs, System. Text. Encoding. GetEncoding ("GB2312 "));

/** // Write the new content to the created HTML page
Sw. WriteLine (strhtml );
Sw. Flush ();
Sw. Close ();
}

/** // Set the hyperlink attributes
HyCreateFile. Text = DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";
HyCreateFile. NavigateUrl = "createHTML/" + DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";
}
Catch (Exception err)
{
Response. Write (err. ToString ());
}
}
Use of the CreateDirectory Method
Using System;
Using System. IO;

Class Test
{
Public static void Main ()
{
// Specify the directory you want to manipulate.
String path = @ "c: \ MyDir ";

Try
{
// Determine whether the directory exists.
If (Directory. Exists (path ))
{
Console. WriteLine ("That path exists already .");
Return;
}

// Try to create the directory.
DirectoryInfo di = Directory. CreateDirectory (path );
Console. WriteLine ("The directory was created successfully at {0}.", Directory. GetCreationTime (path ));

// Delete the directory.
Di. Delete ();
Console. WriteLine ("The directory was deleted successfully .");
}
Catch (Exception e)
{
Console. WriteLine ("The process failed: {0}", e. ToString ());
}
Finally {}
}
}

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.