asp.net C # file operations (append, copy, delete, move files, create directories, recursively delete folders and files)

Source: Internet
Author: User
Tags create directory datetime flush html page html tags readline

ASP tutorial. NET C # File operations (append, copy, delete, move file, create directory, recursively delete folder and file)
C # Append, copy, delete, move files, create directories, recursively delete folders and files, assign all content under a folder to the target folder, Detele all content under the specified folder, read text files, get file lists, read log files, write to log files, create HTML Use of file and CreateDirectory methods
C # Append files

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 # Copy files
String Orignfile,newfile;
Orignfile = Server.MapPath (".") + "Mytext.txt";
NewFile = Server.MapPath (".") + "Mytextcopy.txt";
File.Copy (orignfile,newfile,true);
C # Delete Files
String delfile = Server.MapPath (".") + "Mytextcopy.txt";
File.delete (Delfile);
C # moving files
String Orignfile,newfile;
Orignfile = Server.MapPath (".") + "Mytext.txt";
NewFile = Server.MapPath (".") + "Mytextcopy.txt";
File.move (Orignfile,newfile);
C # Create a directory
Create a directory C:sixage
DirectoryInfo d=directory.createdirectory ("C:sixage");
D1 point to C:sixagesixage1
DirectoryInfo d1=d.createsubdirectory ("Sixage1");
D2 point to C:sixagesixage1sixage1_1
DirectoryInfo d2=d1.createsubdirectory ("sixage1_1");
Set the current directory to C:sixage
Directory.setcurrentdirectory ("C:sixage");
Create a directory C:sixagesixage2
Directory.CreateDirectory ("Sixage2");
Create a directory C:sixagesixage2sixage2_1
Directory.CreateDirectory ("Sixage2sixage2_1");
Delete folders and files recursively
<%@ page language=c#%>
<%@ Import namespace= "System.IO"%>
<script_ runat=server>
public void DeleteFolder (string dir)
{
if (Directory.Exists (dir))//If there is a deletion of this folder
{
foreach (String D in Directory.getfilesystementries (dir))
{
if (file.exists (d))
File.delete (d); Delete files directly from them
Else
DeleteFolder (d); recursively deletes subfolders
}
Directory.delete (dir); Delete an empty folder
Response.Write (dir+ "folder deletion succeeded");
}
Else
Response.Write (dir+ "This folder does not exist"); Prompts if the folder does not exist
}
protected void Page_Load (object sender, EventArgs e)
{
String dir= "D:gbook11";
DeleteFolder (dir); Call Function Delete Folder
}

// ======================================================
Implement a static method to copy all content under the specified folder to the target folder
If the destination folder is read-only, an error occurs.
April 18april2005 in Stu
// ======================================================
public static void Copydir (String srcpath,string aimpath)
{
Try
{
Checks whether the destination directory ends with a directory split character if it is not added
if (Aimpath[aimpath.length-1]!= Path.directoryseparatorchar)
Aimpath + = Path.directoryseparatorchar;
Determine if the target directory exists if it does not exist the new
if (!directory.exists (Aimpath)) directory.createdirectory (Aimpath);
Gets a list of files in the source directory that contains an array of files and directory paths
If you point to the file below the copy destination file and not the directory, use the following method
string[] filelist = Directory.GetFiles (Srcpath);
string[] filelist = directory.getfilesystementries (Srcpath);
Iterate through all the files and directories
foreach (string file in FileList)
{
First as a directory processing if there is this directory recursively copy the file below the directory
if (directory.exists (file))
Copydir (file,aimpath+path.getfilename (file));
Otherwise direct copy file
Else
File.Copy (file,aimpath+path.getfilename (file), true);
}
}
catch (Exception e)
{
MessageBox.Show (E.tostring ());
}
}
// ======================================================
Implementing a static method will specify all the contents under the folder Detele
The test should be handled with care and cannot be recovered after deletion.
// ======================================================
public static void Deletedir (String aimpath)
{
Try
{
Checks whether the destination directory ends with a directory split character if it is not added
if (Aimpath[aimpath.length-1]!= Path.directoryseparatorchar)
Aimpath + = Path.directoryseparatorchar;
Gets a list of files in the source directory that contains an array of files and directory paths
If you point to the file below the delete target file without the directory, use the following method
string[] filelist = Directory.GetFiles (Aimpath);
string[] filelist = directory.getfilesystementries (Aimpath);
Iterate through all the files and directories
foreach (string file in FileList)
{
First as a directory processing if there is this directory recursively delete the file below the directory
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 (Exception e)
{
MessageBox.Show (E.tostring ());
}
}
Need to reference namespaces:
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);
}
Get the name of the folder you want to copy
String strfoldername = Strfrompath.substring (Strfrompath.lastindexof ("") + 1,strfrompath.length- Strfrompath.lastindexof ("")-1);
Create a source folder in the destination folder if there are no source folders 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 Files
for (int i = 0;i < strfiles.length;i++)
{
Gets the file name of the copy, takes only the filename, and the address is truncated.
String strFileName = Strfiles[i].substring (Strfiles[i].lastindexof ("") + 1,strfiles[i].length-strfiles[i]. LastIndexOf ("")-1);
Start copying file, true to overwrite file with same name
File.Copy (Strfiles[i],strtopath + "" + strFolderName + "" + strfilename,true);
}

Create a DirectoryInfo instance
DirectoryInfo dirinfo = new DirectoryInfo (Strfrompath);
To get all the subfolder names under the source folder
directoryinfo[] Zipath = Dirinfo.getdirectories ();
for (int j = 0;j < zipath.length;j++)
{
Get all child folder names
String Strzipath = Strfrompath + "" + zipath[j].tostring ();
Take the resulting subfolder as a new source folder and start a new round of copies from scratch
CopyFolder (Strzipath,strtopath + "" + strfoldername);
}
}
A Reading text files
/**////<summary>
Reading text files
</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 ("Please select a text file");
}
Else
{
StreamReader filestream = new StreamReader (txtfilepath,encoding.default);
Txtcontent.text = Filestream.readtoend ();
Filestream.close ();
}
}
}
Two Get file List
/**////<summary>
Get file List
</summary>
private void Getfilelist ()
{
String Strcurdir,filename,fileext;

/**////File Size
Long filesize;

/**////the last modification time;
DateTime filemodify;

/**////initialization
if (!ispostback)
{
When/**////initializes, it defaults to the directory where the current page is located
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 ();

/**////Dynamically adding cell contents
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);

/**////a directory Reference object for the current directory
DirectoryInfo dirinfo = new DirectoryInfo (txtcurdir.text);

/**////loops to determine the files and directories in the current directory
foreach (FileSystemInfo FSI in Dirinfo.getfilesysteminfos ())
{
filename = "";
Fileext = "";
FileSize = 0;

/**////if it's a file
If (FSI is FileInfo)
{
fi = (FileInfo) FSI;

/**////get filename
filename = fi.name;

/**////to get file extension
Fileext = fi.extension;

/**////gets the size of the file
FileSize = Fi.length;

/**////to get the last modification time of the file
Filemodify = Fi.lastwritetime;
}

/**////otherwise is the directory
Else
{
dir = (DirectoryInfo) FSI;

/**////Get directory Name
filename = dir.name;

/**////gets the last modification time of the catalog
Filemodify = Dir.lastwritetime;

/**////settings file has the extension "folder"
Fileext = "folder";
}

/**////Dynamically Add Table contents
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);
}
}
Three Reading log files
/**////<summary>
Reading log files
</summary>
private void Readlogfile ()
{
/**////reads a log file from a specified directory to open or create a form
FileStream fs = new FileStream (Server.MapPath ("upedfile") + "LogFile.txt", FileMode.OpenOrCreate, FileAccess.Read);

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

/**////initializes the string to a length of 0
output.length = 0;

/**////to create a read stream for the file stream created above
StreamReader read = new StreamReader (FS);

/**////sets the starting position of the current stream as the starting point for the file stream
Read.basestream.seek (0, Seekorigin.begin);

/**////Read files
while (Read.peek () >-1)
{
/**////a line of files and wraps
Output.append (Read.readline () + "n");
}

/**////turn off the read data stream
Read.close ();

/**////returns the contents of a read log file
return output.tostring ();
}
Four Write to log file

/**////<summary>
Write to log file
</summary>
<param ></param>
private void Writelogfile (string input)
{
/**////Specifies the directory of the log file
String fname = Server.MapPath ("upedfile") + "logfile.txt";
/**////Definition File Information object
FileInfo finfo = new FileInfo (fname);

/**////determine if the file exists and is greater than 2k
if (finfo.exists && finfo.length > 2048)
{
/**////Delete the file
Finfo.delete ();
}
/**////Create a write-only file stream
using (FileStream fs = Finfo.openwrite ())
{
/**////creates a write stream 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);

W.write ("Nlog entry:");

/**////writes the current system time and wraps the line
W.write ("{0} {1} rn", Datetime.now.tolongtimestring (), datetime.now.tolongdatestring ());

/**////writes the contents of the log and wraps the line
W.write (input + "n");

/**////write to------------------------------------"and line wrap
W.write ("------------------------------------n");

/**////empties the buffer contents and writes the buffer contents to the underlying stream
W.flush ();

/**////closes the write data stream
W.close ();
}
}
Five C # Create HTML file
/**////<summary>
Create an HTML file
</summary>
private void Createhtmlfile ()
{
/**////definition and number of HTML tags in a consistent array
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;

/**////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 ());
}
/**////assigning values to a tagged 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

/**////generates HTML files based on the new content above
Try
{
/**////Specifies the HTML file to be generated
String fname = Server.MapPath ("createhtml") + "" + datetime.now.tostring ("YYYYMMDDHHMMSS") + ". html";

/**////replaces tags in HTML template files with new content
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 open or write
using (FileStream fs = Finfo.openwrite ())
{
/**////creates a write stream 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
Sw.writeline (strhtml);
Sw.flush ();
Sw.close ();
}

/**////Set Hyperlink Properties
Hycreatefile.text = datetime.now.tostring ("YYYYMMDDHHMMSS") + ". html";
Hycreatefile.navigateurl = "createhtml/" +datetime.now.tostring ("YYYYMMDDHHMMSS") + ". html";
}
catch (Exception err)
{
Response.Write (Err.tostring ());
}
}
The use of CreateDirectory method
using System;
Using System.IO;

Class Test
{
public static void Main ()
{
Specify the directory for your 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 is 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.