C# 文件操作 全收录 追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件.......
本文收集了目前最為常用的C#經(jīng)典操作文件的方法,具體內(nèi)容如下:C#追加、拷貝、刪除、移動(dòng)文件、創(chuàng)建目錄、遞歸刪除文件夾及文件、指定文件夾下 面的所有內(nèi)容copy到目標(biāo)文件夾下面、指定文件夾下面的所有內(nèi)容Detele、讀取文本文件、獲取文件列表、讀取日志文件、寫(xiě)入日志文件、創(chuàng)建HTML 文件、CreateDirectory方法的使用
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#移動(dòng)文件
string OrignFile,NewFile;
OrignFile = Server.MapPath(".")+"\\myText.txt";
NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
File.Move(OrignFile,NewFile);
C#創(chuàng)建目錄
// 創(chuàng)建目錄c:\sixAge
DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge");
// d1指向c:\sixAge\sixAge1
DirectoryInfo d1=d.CreateSubdirectory("sixAge1");
// d2指向c:\sixAge\sixAge1\sixAge1_1
DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1");
// 將當(dāng)前目錄設(shè)為c:\sixAge
Directory.SetCurrentDirectory("c:\\sixAge");
// 創(chuàng)建目錄c:\sixAge\sixAge2
Directory.CreateDirectory("sixAge2");
// 創(chuàng)建目錄c:\sixAge\sixAge2\sixAge2_1
Directory.CreateDirectory("sixAge2\\sixAge2_1");
遞歸刪除文件夾及文件
<%@ Page Language=C#%>
<%@ Import namespace="System.IO"%>
<script_ runat=server>
public void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在這個(gè)文件夾刪除之
{
foreach(string d in Directory.GetFileSystemEntries(dir))
{
if(File.Exists(d))
File.Delete(d); //直接刪除其中的文件
else
DeleteFolder(d); //遞歸刪除子文件夾
}
Directory.Delete(dir); //刪除已空文件夾
Response.Write(dir+" 文件夾刪除成功");
}
else
Response.Write(dir+" 該文件夾不存在"); //如果文件夾不存在則提示
}
protected void Page_Load (Object sender ,EventArgs e)
{
string Dir="D:\\gbook\\11";
DeleteFolder(Dir); //調(diào)用函數(shù)刪除文件夾
}
// ======================================================
// 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容copy到目標(biāo)文件夾下面
// 如果目標(biāo)文件夾為只讀屬性就會(huì)報(bào)錯(cuò)。
// April 18April2005 In STU
// ======================================================
public static void CopyDir(string srcPath,string aimPath)
{
try
{
// 檢查目標(biāo)目錄是否以目錄分割字符結(jié)束如果不是則添加之
if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判斷目標(biāo)目錄是否存在如果不存在則新建之
if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
// 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
// 如果你指向copy目標(biāo)文件下面的文件而不包含目錄請(qǐng)使用下面的方法
// string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
// 遍歷所有的文件和目錄
foreach(string file in fileList)
{
// 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸Copy該目錄下面的文件
if(Directory.Exists(file))
CopyDir(file,aimPath+Path.GetFileName(file));
// 否則直接Copy文件
else
File.Copy(file,aimPath+Path.GetFileName(file),true);
}
}
catch (Exception e)
{
MessageBox.Show (e.ToString());
}
}
// ======================================================
// 實(shí)現(xiàn)一個(gè)靜態(tài)方法將指定文件夾下面的所有內(nèi)容Detele
// 測(cè)試的時(shí)候要小心操作,刪除之后無(wú)法恢復(fù)。
// ======================================================
public static void DeleteDir(string aimPath)
{
try
{
// 檢查目標(biāo)目錄是否以目錄分割字符結(jié)束如果不是則添加之
if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 得到源目錄的文件列表,該里面是包含文件以及目錄路徑的一個(gè)數(shù)組
// 如果你指向Delete目標(biāo)文件下面的文件而不包含目錄請(qǐng)使用下面的方法
// string[] fileList = Directory.GetFiles(aimPath);
string[] fileList = Directory.GetFileSystemEntries(aimPath);
// 遍歷所有的文件和目錄
foreach(string file in fileList)
{
// 先當(dāng)作目錄處理如果存在這個(gè)目錄就遞歸Delete該目錄下面的文件
if(Directory.Exists(file))
{
DeleteDir(aimPath+Path.GetFileName(file));
}
// 否則直接Delete文件
else
{
File.Delete (aimPath+Path.GetFileName(file));
}
}
//刪除文件夾
System.IO .Directory .Delete (aimPath,true);
}
catch (Exception e)
{
MessageBox.Show (e.ToString());
}
}
需要引用命名空間:
using System.IO;
/** <summary>
/// </summary>
/// <param ></param>
/// <param ></param>
//--------------------------------------------------
//---------------------------------------------------
public static void CopyFolder(string strFromPath,string strToPath)
{
//如果源文件夾不存在,則創(chuàng)建
if (!Directory.Exists(strFromPath))
{
Directory.CreateDirectory(strFromPath);
}
//取得要拷貝的文件夾名
string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") + 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
//如果目標(biāo)文件夾中沒(méi)有源文件夾則在目標(biāo)文件夾中創(chuàng)建源文件夾
if (!Directory.Exists(strToPath + "\\" + strFolderName))
{
Directory.CreateDirectory(strToPath + "\\" + strFolderName);
}
//創(chuàng)建數(shù)組保存源文件夾下的文件名
string[] strFiles = Directory.GetFiles(strFromPath);
//循環(huán)拷貝文件
for(int i = 0;i < strFiles.Length;i++)
{
//取得拷貝的文件名,只取文件名,地址截掉。
string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
//開(kāi)始拷貝文件,true表示覆蓋同名文件
File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);
}
//創(chuàng)建DirectoryInfo實(shí)例
DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
//取得源文件夾下的所有子文件夾名稱
DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
for (int j = 0;j < ZiPath.Length;j++)
{
//獲取所有子文件夾名
string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();
//把得到的子文件夾當(dāng)成新的源文件夾,從頭開(kāi)始新一輪的拷貝
CopyFolder(strZiPath,strToPath + "\\" + strFolderName);
}
}
一.讀取文本文件
/** <summary>
/// 讀取文本文件
/// </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("請(qǐng)選擇文本文件");
}
else
{
StreamReader fileStream = new StreamReader(txtFilePath,Encoding.Default);
txtContent.Text = fileStream.ReadToEnd();
fileStream.Close();
}
}
}
二.獲取文件列表
/** <summary>
/// 獲取文件列表
/// </summary>
private void GetFileList()
{
string strCurDir,FileName,FileExt;
/**文件大小
long FileSize;
/**最后修改時(shí)間;
DateTime FileModify;
/**初始化
if(!IsPostBack)
{
/**初始化時(shí),默認(rèn)為當(dāng)前頁(yè)面所在的目錄
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();
/**動(dòng)態(tài)添加單元格內(nèi)容
td = new TableCell();
td.Controls.Add(new LiteralControl("文件名"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("文件類型"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("文件大小"));
tr.Cells.Add(td);
td = new TableCell();
td.Controls.Add(new LiteralControl("最后修改時(shí)間"));
tr.Cells.Add(td);
tableDirInfo.Rows.Add(tr);
/**針對(duì)當(dāng)前目錄建立目錄引用對(duì)象
DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);
/**循環(huán)判斷當(dāng)前目錄下的文件和目錄
foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
{
FileName = "";
FileExt = "";
FileSize = 0;
/**如果是文件
if(fsi is FileInfo)
{
fi = (FileInfo)fsi;
/**取得文件名
FileName = fi.Name;
/**取得文件的擴(kuò)展名
FileExt = fi.Extension;
/**取得文件的大小
FileSize = fi.Length;
/**取得文件的最后修改時(shí)間
FileModify = fi.LastWriteTime;
}
/**否則是目錄
else
{
dir = (DirectoryInfo)fsi;
/**取得目錄名
FileName = dir.Name;
/**取得目錄的最后修改時(shí)間
FileModify = dir.LastWriteTime;
/**設(shè)置文件的擴(kuò)展名為"文件夾"
FileExt = "文件夾";
}
/**動(dòng)態(tài)添加表格內(nèi)容
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()+"字節(jié)"));
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);
}
}
三.讀取日志文件
/** <summary>
/// 讀取日志文件
/// </summary>
private void ReadLogFile()
{
/**從指定的目錄以打開(kāi)或者創(chuàng)建的形式讀取日志文件
FileStream fs = new FileStream(Server.MapPath("upedFile")+"\\logfile.txt", FileMode.OpenOrCreate, FileAccess.Read);
/**定義輸出字符串
StringBuilder output = new StringBuilder();
/**初始化該字符串的長(zhǎng)度為0
output.Length = 0;
/**為上面創(chuàng)建的文件流創(chuàng)建讀取數(shù)據(jù)流
StreamReader read = new StreamReader(fs);
/**設(shè)置當(dāng)前流的起始位置為文件流的起始點(diǎn)
read.BaseStream.Seek(0, SeekOrigin.Begin);
/**讀取文件
while (read.Peek() > -1)
{
/**取文件的一行內(nèi)容并換行
output.Append(read.ReadLine() + "\n");
}
/**關(guān)閉釋放讀數(shù)據(jù)流
read.Close();
/**返回讀到的日志文件內(nèi)容
return output.ToString();
}
四.寫(xiě)入日志文件
/** <summary>
/// 寫(xiě)入日志文件
/// </summary>
/// <param ></param>
private void WriteLogFile(string input)
{
/**指定日志文件的目錄
string fname = Server.MapPath("upedFile") + "\\logfile.txt";
/**定義文件信息對(duì)象
FileInfo finfo = new FileInfo(fname);
/**判斷文件是否存在以及是否大于2K
if ( finfo.Exists && finfo.Length > 2048 )
{
/**刪除該文件
finfo.Delete();
}
/**創(chuàng)建只寫(xiě)文件流
using(FileStream fs = finfo.OpenWrite())
{
/**根據(jù)上面創(chuàng)建的文件流創(chuàng)建寫(xiě)數(shù)據(jù)流
StreamWriter w = new StreamWriter(fs);
/**設(shè)置寫(xiě)數(shù)據(jù)流的起始位置為文件流的末尾
w.BaseStream.Seek(0, SeekOrigin.End);
w.Write("\nLog Entry : ");
/**寫(xiě)入當(dāng)前系統(tǒng)時(shí)間并換行
w.Write("{0} {1} \r\n",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
/**寫(xiě)入日志內(nèi)容并換行
w.Write(input + "\n");
/**寫(xiě)入------------------------------------“并換行
w.Write("------------------------------------\n");
/**清空緩沖區(qū)內(nèi)容,并把緩沖區(qū)內(nèi)容寫(xiě)入基礎(chǔ)流
w.Flush();
/**關(guān)閉寫(xiě)數(shù)據(jù)流
w.Close();
}
}
五.C#創(chuàng)建HTML文件
/** <summary>
/// 創(chuàng)建HTML文件
/// </summary>
private void CreateHtmlFile()
{
/**定義和html標(biāo)記數(shù)目一致的數(shù)組
string[] newContent = new string[5];
StringBuilder strhtml = new StringBuilder();
try
{
/**創(chuàng)建StreamReader對(duì)象
using (StreamReader sr = new StreamReader(Server.MapPath("createHTML") + "\\template.html"))
{
String oneline;
/**讀取指定的HTML文件模板
while ((oneline = sr.ReadLine()) != null)
{
strhtml.Append(oneline);
}
sr.Close();
}
}
catch(Exception err)
{
/**輸出異常信息
Response.Write(err.ToString());
}
/**為標(biāo)記數(shù)組賦值
newContent[0] = txtTitle.Text;//標(biāo)題
newContent[1] = "BackColor='#cccfff'";//背景色
newContent[2] = "#ff0000";//字體顏色
newContent[3] = "100px";//字體大小
newContent[4] = txtContent.Text;//主要內(nèi)容
/**根據(jù)上面新的內(nèi)容生成html文件
try
{
/**指定要生成的HTML文件
string fname = Server.MapPath("createHTML") +"\\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html";
/**替換html模版文件里的標(biāo)記為新的內(nèi)容
for(int i=0;i < 5;i++)
{
strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
}
/**創(chuàng)建文件信息對(duì)象
FileInfo finfo = new FileInfo(fname);
/**以打開(kāi)或者寫(xiě)入的形式創(chuàng)建文件流
using(FileStream fs = finfo.OpenWrite())
{
/**根據(jù)上面創(chuàng)建的文件流創(chuàng)建寫(xiě)數(shù)據(jù)流
StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
/**把新的內(nèi)容寫(xiě)到創(chuàng)建的HTML頁(yè)面中
sw.WriteLine(strhtml);
sw.Flush();
sw.Close();
}
/**設(shè)置超級(jí)鏈接的屬性
hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";
hyCreateFile.NavigateUrl = "createHTML/"+DateTime.Now.ToString("yyyymmddhhmmss")+".html";
}
catch(Exception err)
{
Response.Write (err.ToString());
}
}
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 {}
}
}
?
http://www.cnblogs.com/zhuzhiyuan/archive/2011/04/22/2024485.html
轉(zhuǎn)載于:https://blog.51cto.com/flydragon0815/1066242
總結(jié)
以上是生活随笔為你收集整理的C# 文件操作 全收录 追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件.......的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 短消息编解码算法
- 下一篇: asp.net C# 计算运算耗时时间