C#追加文件
StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");
sw.WriteLine("追逐理想");
sw.WriteLine("kzlll");
sw.WriteLine(".NET笔记");
sw.Flush();
sw.Close();
C#拷贝文件
string OrignFile,NewFile;
OrignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Copy(OrignFile,NewFile,true);
C#删除文件
string delFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Delete(delFile);
C#移动文件
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: \ sixAge \ sixAge1
DirectoryInfo d1 = d .CreateSubdirectory ( "sixAge1");
// D2 point to c: \ sixAge \ sixAge1 \ sixAge1_1
DirectoryInfo D2 = d1.CreateSubdirectory ( "sixAge1_1");
// set the current directory 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 ");
recursion delete folders and files
- <% @ PAGELANGUAGE = C #%>
-
〈%@Importnamespace="System.IO"%〉
-
〈Scriptrunat=server〉
-
publicvoidDeleteFolder(stringdir)
-
{
-
if (Directory.Exists (dir)) // if
-
The existence of this folder deleted
-
{
-
foreach(stringdinDirectory.
-
GetFileSystemEntries (dir))
-
{
-
if(File.Exists(d))
-
File.Delete (d); // delete the files
-
else
-
DeleteFolder (d); // delete subfolders recursively
-
}
-
Directory.Delete (dir); // delete empty folders
-
Response.Write (dir + "folder deleted successfully");
-
}
-
else
-
Response.Write (dir + "The folder does not exist"); // if
-
Folder does not exist then the prompt
-
}
-
protectedvoidPage_Load(Object
-
crosses, EventArgse)
-
{
-
stringDir="D:\\gbook\\11";
-
DeleteFolder (Dir); // call the function to delete a folder
-
}
-
-
-
//========================================
-
// static method to achieve a specified folder the following copy all the contents to the destination folder below
-
// If the destination folder is read-only attribute will throw an error.
-
//========================================
-
publicstaticvoidCopyDir(stringsrcPath,
-
stringaimPath)
-
{
-
try
-
{
-
// Check if the target directory to directory split word
-
Break ends, if not add it
-
if(aimPath[aimPath.Length-1]!= Path.DirectorySeparatorChar)
-
aimPath+=Path.DirectorySeparatorChar;
-
// determine the target directory exists, if it does not exist New
-
if(!Directory.Exists(aimPath))Directory.CreateDirectory(aimPath);
-
// get the source directory of the file list,
-
The inside is an array that contains the file and directory path
-
// If you point to copy the target file the following documents
-
Does not contain a directory Please use the following method
-
//string[]fileList=Directory.GetFiles(srcPath);
-
string[]fileList=Directory.GetFileSystemEntries(srcPath);
-
// loop through all files and directories
-
foreach(stringfileinfileList)
-
{
-
// If there are to deal with this as a directory
-
Copy directories recursively the directory file
-
if(Directory.Exists(file))
-
CopyDir(file,aimPath+Path.GetFileName(file));
-
// Copy the file directly otherwise
-
else
-
File.Copy(file,aimPath+Path.GetFileName(file),true);
-
}
-
}
-
catch (Exception)
-
{
-
MessageBox.Show(e.ToString());
-
}
-
}
-
//========================================
-
// implement a static method of the specified folder below all the contents Detele
-
// test of time to be careful, can not be recovered after deletion.
-
//========================================
-
publicstaticvoidDeleteDir(stringaimPath)
-
{
-
try
-
{
-
// Check if the target directory to directory split word
-
Break ends, if not add it
-
if(aimPath[aimPath.Length-1]!=
-
Path.DirectorySeparatorChar)
-
aimPath+=Path.DirectorySeparatorChar;
-
// get the source directory of the file list,
-
The inside is an array that contains the file and directory path
-
// If you point to Delete the target file the following
-
File does not contain directory please use the following method
-
//string[]fileList=
-
Directory.GetFiles(aimPath);
-
string[]fileList=
-
Directory.GetFileSystemEntries(aimPath);
-
// loop through all files and directories
-
foreach(stringfileinfileList)
-
{
-
// If there are to deal with this as a directory
-
Recursive directory to the directory Delete the following files
-
if(Directory.Exists(file))
-
{
-
DeleteDir(aimPath+Path.GetFileName(file));
-
}
-
// Delete the file directly otherwise
-
else
-
{
-
File.Delete(aimPath+Path.GetFileName(file));
-
}
-
}
-
// delete a folder
-
System.IO.Directory.Delete(aimPath,true);
-
}
-
catch (Exception)
-
{
-
MessageBox.Show(e.ToString());
-
}
-
}
-
-
You need to reference the namespace:
-
usingSystem.IO;
-
///〈summary〉
-
/// Copy the folder (including subfolders) to a specified folder,
-
Source folder and destination folder required absolute path.
-
Format: CopyFolder (source folder, destination folder);
-
///〈/summary〉
-
///〈paramname="strFromPath"〉〈/param〉
-
///〈paramname="strToPath"〉〈/param〉
-
-
//----------------------------------------
-
-
//----------------------------------------
-
publicstaticvoidCopyFolder(stringstrFromPath,
-
stringstrToPath)
-
{
-
// 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
-
stringstrFolderName=strFromPath.Substring(
-
strFromPath.LastIndexOf("\")+1,strFromPath.
-
Length-strFromPath.LastIndexOf("\")-1);
-
-
// If the file does not target the source folder source folder is created in the destination folder
-
if(!Directory.Exists(strToPath+"\"
-
+strFolderName))
-
{
-
Directory.CreateDirectory(strToPath+"\"
-
+strFolderName);
-
}
-
// create an array to save the source folder under the file name
-
string[]strFiles=Directory.GetFiles(strFromPath);
-
-
// Loop copy files
-
for(inti=0;i〈strFiles.Length;i++)
-
{
-
// Get a copy of the file name, just take the file name, address amputated.
-
stringstrFileName=strFiles[i].Substring(
-
strFiles[i].LastIndexOf("\")+1,
-
strFiles[i].Length-strFiles[i].
-
LastIndexOf("\")-1);
-
// start copying files, true representation covering the same file
-
File.Copy(strFiles[i],strToPath+"\"
-
+strFolderName+"\"+strFileName,true);
-
}
-
-
// Create instance DirectoryInfo
-
DirectoryInfodirInfo = newDirectoryInfo (
-
strFromPath);
-
// get all subfolders of the source folder under the folder name
-
DirectoryInfo [] ZiPath = dirInfo.GetDirectories ();
-
for(intj=0;j〈ZiPath.Length;j++)
-
{
-
// Get all the sub-folder name
-
stringstrZiPath=strFromPath+"\"+
-
ZiPath[j].ToString();
-
// get the subfolders of the folder as a new source folder,
-
From the beginning of a new round of copy
-
CopyFolder(strZiPath,strToPath+"\"+
-
strFolderName);
-
}
-
}
-
C # file operations: reading text files
-
1/// 〈summary〉
-
2 /// read a text file
-
3/// 〈/summary〉
-
4private void ReadFromTxtFile()
-
5{
-
6 if(filePath.PostedFile.
-
FileName != "")
-
7 {
-
8 txtFilePath =
-
filePath.PostedFile.FileName;
-
9 fileExtName =
-
txtFilePath.Substring(txtFilePath.
-
LastIndexOf(".")+1,3);
-
10
-
11 if(fileExtName !="txt" &&
-
fileExtName != "TXT")
-
12 {
-
13 Response.Write ( "Select Text File");
-
14 }
-
15 else
-
16 {
-
17 StreamReader fileStream =
-
new StreamReader(txtFilePath,Encoding.Default);
-
18 txtContent.Text = fileStream.ReadToEnd();
-
19 fileStream.Close();
-
20 }
-
21 }
-
22 }
-
C # file: Obtain the file list
-
1/// 〈summary〉
-
2 /// Gets the file list
-
3/// 〈/summary〉
-
4private void GetFileList()
-
5{
-
6 string strCurDir,FileName,FileExt;
-
7
-
8 /// File Size
-
9 long FileSize;
-
10
-
11 /// last modified;
-
12 DateTime FileModify;
-
13
-
14 /// initialization
-
15 if(!IsPostBack)
-
16 {
-
17 /// initialization, the default is the directory where the current page
-
18 strCurDir = Server.MapPath(".");
-
19 lblCurDir.Text = strCurDir;
-
20 txtCurDir.Text = strCurDir;
-
21 }
-
22 else
-
23 {
-
24 strCurDir = txtCurDir.Text;
-
25 txtCurDir.Text = strCurDir;
-
26 lblCurDir.Text = strCurDir;
-
27 }
-
28 FileInfo fi;
-
29 Directory info you;
-
30 TableCell td;
-
31 TableRow tr;
-
32 tr = new TableRow();
-
33
-
34 /// cell contents dynamically added
-
35 td = new TableCell();
-
36 td.Controls.Add(new LiteralControl(
-
"file name"));
-
37 tr.Cells.Add(td);
-
38 td = new TableCell();
-
Td.Controls.Add 39 (new new LiteralControl ( "File Types"));
-
40 tr.Cells.Add(td);
-
41 td = new TableCell();
-
Td.Controls.Add 42 is (the LiteralControl new new ( "file size"));
-
43 tr.Cells.Add(td);
-
44 td = new TableCell();
-
Td.Controls.Add 45 (the LiteralControl new new ( "last modified time"));
-
46 tr.Cells.Add(td);
-
47
-
48 tableDirInfo.Rows.Add(tr);
-
49
-
50 /// establish reference objects for the current directory
-
51 DirectoryInfo dirInfo = new DirectoryInfo( txtCurDir.Text);
-
52
-
53 /// cycle to determine the current file and directory of
-
54 foreach(FileSystemInfo fsi in dirInfo.
-
GetFileSystemInfos())
-
55 {
-
56 FileName = "";
-
57 FileExt = "";
-
58 FileSize = 0;
-
59
-
If the file is 60 ///
-
61 if(fsi is FileInfo)
-
62 {
-
63 fi = (FileInfo)fsi;
-
64
-
65 /// Gets file name
-
66 FileName = fi.Name;
-
67
-
68 /// obtain the file extension
-
69 FileExt = fi.Extension;
-
70
-
71 /// Gets file size
-
72 FileSize = fi.Length;
-
73
-
Last modified 74 /// Gets file
-
75 FileModify = fi.LastWriteTime;
-
76 }
-
77
-
78 /// otherwise directory
-
79 else
-
80 {
-
81 dir = (Directory Information) fsi;
-
82
-
83 /// get directory name
-
84 FileName = dir.Name;
-
85
-
86 /// obtain the directory last modified
-
87 FileModify = dir.LastWriteTime;
-
88
-
89 /// extension settings file named "Folder"
-
90 FileExt = "folder";
-
91 }
-
92
-
93 /// add dynamic table of contents
-
94 tr = new TableRow();
-
95 td = new TableCell();
-
96 td.Controls.Add(new LiteralControl( FileName));
-
97 tr.Cells.Add(td);
-
98 td = new TableCell();
-
99 td.Controls.Add(new LiteralControl( FileExt));
-
100 tr.Cells.Add(td);
-
101 td = new TableCell();
-
102 td.Controls.Add(new LiteralControl( FileSize.ToString()+"字节"));
-
103 tr.Cells.Add(td);
-
104 td = new TableCell();
-
105 td.Controls.Add(new LiteralControl( FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
-
106 tr.Cells.Add(td);
-
107 tableDirInfo.Rows.Add(tr);
-
108 }
-
109}
-
C # file operations: reading the log file
-
1/// 〈summary〉
-
2 /// read log files
-
3/// 〈/summary〉
-
4private void ReadLogFile()
-
5{
-
6 /// to play from the specified directory open or create a form read log files
-
7 FileStream fs =
-
new FileStream(Server.MapPath("upedFile"
-
)+"\\logfile.txt", FileMode.OpenOrCreate,
-
FileAccess.Read);
-
8
-
9 /// defined output string
-
10 StringBuilder output = new StringBuilder();
-
11
-
12 /// length of the string is initialized 0
-
13 output.Length = 0;
-
14
-
15 /// file is created above to read the data stream flow creation
-
16 StreamReader read = new StreamReader(fs);
-
17
-
18 /// set the starting point for the beginning of the current stream file stream
-
19 read.BaseStream.Seek(0, SeekOrigin.Begin);
-
20
-
21 /// read the file
-
22 while (read.Peek() 〉 -1)
-
23 {
-
24 /// the contents of his party to take the file and line feed
-
25 output.Append(read.ReadLine() + "\n");
-
26 }
-
27
-
28 /// Close release the read data stream
-
29 read.Close();
-
30
-
31 /// returns the contents of the log file read
-
32 return output.ToString();
-
}
-
-
-
C # file operations: write to the log file
-
1/// 〈summary〉
-
2 /// written to the log file
-
3/// 〈/summary〉
-
4/// 〈param name="input"〉〈/param〉
-
5private void WriteLogFile(string input)
-
6{
-
7 /// directory specified log file
-
8 string fname = Server.MapPath("upedFile") + "\\logfile.txt";
-
9 /// definition file information objects
-
10 FileInfo finfo = new FileInfo(fname);
-
11
-
/// 12 determines whether the file exists and is greater than 2K
-
13 if ( finfo.Exists && finfo.Length 〉 2048 )
-
14 {
-
15 /// delete the file
-
16 finfo.Delete();
-
17 }
-
18 /// create a write-only file stream
-
19 using(FileStream fs = finfo.OpenWrite())
-
20 {
-
21 /// stream to create a write data stream based on the file created above
-
22 StreamWriter w = new StreamWriter(fs);
-
23
-
/// 24 disposed at the end of the write start position of the data stream as a stream file
-
25 w.BaseStream.Seek(0, SeekOrigin.End);
-
26
-
27 /// write "Log Entry:"
-
28 w.Write("\nLog Entry : ");
-
29
-
30 /// write current system time and line
-
31 w.Write("{0} {1} \r\n", DateTime.Now.
-
ToLongTimeString ()
-
32 DateTime.Now.ToLongDateString());
-
33
-
/// content written to the log 34 and wrap
-
35 w.Write(input + "\n");
-
36
-
---------------- 37 /// write "and line
-
38 w.Write("------------------\n");
-
39
-
40 /// empty the buffer contents, and the contents of the buffer written to the underlying stream
-
41 w.Flush();
-
42
-
43 /// close the write data stream
-
44 w.Close();
-
45 }
-
46}
-
C # file: Create an HTML file
-
1/// 〈summary〉
-
2 // Create an HTML file
-
3/// 〈/summary〉
-
4private void CreateHtmlFile()
-
5{
-
/// The number of defined and consistent 6 html tag array
-
7 string[] newContent = new string[5];
-
8 StringBuilder strhtml =
-
new StringBuilder();
-
9 try
-
10 {
-
11 /// create StreamReader object
-
12 using (StreamReader sr =
-
new StreamReader(Server.MapPath("createHTML") + "\\template.html"))
-
13 {
-
14 String oneline;
-
15
-
16 /// read the specified HTML file template
-
17 while ((oneline = sr.ReadLine())
-
!= null)
-
18 {
-
19 strhtml.Append(oneline);
-
20 }
-
21 sr.Close();
-
22 }
-
23 }
-
24 catch(Exception err)
-
25 {
-
26 /// output abnormality information
-
27 Response.Write(err.ToString());
-
28 }
-
29 /// marked array assignment
-
30 newContent [0] = txtTitle.Text; // title
-
31 newContent [1] = "BackColor = '# cccfff'"; // background color
-
32 newContent [2] = "# ff0000"; // font color
-
33 newContent [3] = "100px"; // Font Size
-
34 newContent [4] = txtContent.Text; // main content
-
35
-
36 /// generated html file according to the new content of the above
-
37 try
-
38 {
-
39 /// Specifies the generated HTML file
-
40 string fname = Server.MapPath( "createHTML") +"\" + DateTime.Now.ToString(
-
"yyyymmddhhmmss") + ".html";
-
41
-
42 /// replace html template file is marked as new content
-
43 for(int i=0;i 〈 5;i++)
-
44 {
-
45 strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
-
46 }
-
47 // create an object file information
-
48 FileInfo finfo = new FileInfo(fname);
-
49
-
50 // Create a file stream in the form of open or write
-
51 using(FileStream fs = finfo.OpenWrite())
-
52 {
-
53 /// stream to create a write data stream based on the file created above
-
54 StreamWriter sw = new StreamWriter(fs,System.
-
Text.Encoding.GetEncoding("GB2312"));
-
55
-
56 /// HTML pages to create new content written in
-
57 sw.WriteLine(strhtml);
-
58 sw.Flush();
-
59 sw.Close();
-
60 }
-
61
-
62 /// set the hyperlink property
-
63 hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";
-
64 hyCreateFile.NavigateUrl = "
-
createHTML/"+DateTime.Now.ToString(" yyyymmddhhmmss")+".html";65 }
-
66 catch(Exception err)
-
67 {
-
68 Response.Write (err.ToString());
-
69 }
-
}
-
CreateDirectory方法的使用
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 {}
}
}C # modify the file or folder name
Reference documentation, made a demo, move () method is actually renamed; In addition, the use of moveto DirectoryInfo is achievable.
sourceCode:
string srcFileName = @"D:/a.txt";
string destFileName = @"D:/b.txt";string srcFolderPath = @"D:/1";
string destFolderPath = @"D:/6";
//方法一
if (System.IO.File.Exists(srcFileName))
{
System.IO.File.Move(srcFileName, destFileName);
}
if (System.IO.Directory.Exists(srcFolderPath))
{
System.IO.Directory.Move(srcFolderPath, destFolderPath);
}
//方法二
if (System.IO.File.Exists(srcFileName))
{
System.IO.FileInfo file = new System.IO.FileInfo(srcFileName);
file.MoveTo(destFileName);
}
if (System.IO.Directory.Exists(srcFolderPath))
{
System.IO.DirectoryInfo folder = new System.IO.DirectoryInfo(srcFolderPath);
folder.MoveTo(destFolderPath);
}
Transfer from https://www.cnblogs.com/Zero0602/p/6961656.html