C#對(duì)文件/文件夾操作代碼匯總
更新時(shí)間:2015年04月30日 09:42:50 投稿:hebedich
有關(guān)文件的操作的內(nèi)容非常多,不過(guò)幾乎都是從下面的這些基礎(chǔ)方法中演化出來(lái)的。比如對(duì)內(nèi)容的修改,不外乎就是加上點(diǎn)字符串操作或者流操作。還有其它一些特別的內(nèi)容,等在開發(fā)項(xiàng)目中具體遇到后再添加。
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ù)。
// April 18April2005 In STU
// ======================================================
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>
/// 拷貝文件夾(包括子文件夾)到指定文件夾下,源文件夾和目標(biāo)文件夾均需絕對(duì)路徑. 格式: CopyFolder(源文件夾,目標(biāo)文件夾);
/// </summary>
/// <param name="strFromPath"></param>
/// <param name="strToPath"></param>
//--------------------------------------------------
//作者:明天去要飯 QQ:305725744
//---------------------------------------------------
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)文件夾中沒有源文件夾則在目標(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);
//開始拷貝文件,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)成新的源文件夾,從頭開始新一輪的拷貝
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()
{
/**////從指定的目錄以打開或者創(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();
}
四.寫入日志文件
//// <summary>
/// 寫入日志文件
/// </summary>
/// <param name="input"></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)建只寫文件流
using(FileStream fs = finfo.OpenWrite())
{
/**////根據(jù)上面創(chuàng)建的文件流創(chuàng)建寫數(shù)據(jù)流
StreamWriter w = new StreamWriter(fs);
/**////設(shè)置寫數(shù)據(jù)流的起始位置為文件流的末尾
w.BaseStream.Seek(0, SeekOrigin.End);
/**////寫入“Log Entry : ”
w.Write("\nLog Entry : ");
/**////寫入當(dāng)前系統(tǒng)時(shí)間并換行
w.Write("{0} {1} \r\n", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
/**////寫入日志內(nèi)容并換行
w.Write(input + "\n");
/**////寫入------------------------------------“并換行
w.Write("------------------------------------\n");
/**////清空緩沖區(qū)內(nèi)容,并把緩沖區(qū)內(nèi)容寫入基礎(chǔ)流
w.Flush();
/**////關(guān)閉寫數(shù)據(jù)流
w.Close();
}
}
五.創(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);
/**////以打開或者寫入的形式創(chuàng)建文件流
using(FileStream fs = finfo.OpenWrite())
{
/**////根據(jù)上面創(chuàng)建的文件流創(chuàng)建寫數(shù)據(jù)流
StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
/**////把新的內(nèi)容寫到創(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());
}
}
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
您可能感興趣的文章:
- C# 遍歷文件夾子目錄下所有圖片及遍歷文件夾下的文件
- C#遍歷文件夾及子目錄下所有圖片
- C#遍歷文件夾及其子目錄的完整實(shí)現(xiàn)方法
- C#簡(jiǎn)單遍歷指定文件夾中所有文件的方法
- C#刪除只讀文件或文件夾(解決File.Delete無(wú)法刪除文件)
- C#搜索文字在文件及文件夾中出現(xiàn)位置的方法
- C#實(shí)現(xiàn)復(fù)制文件夾中文件到另一個(gè)文件夾的方法
- C#將文件復(fù)制到指定文件夾并整理
- C#實(shí)現(xiàn)獲取文件夾大小的方法
- C#顯示文件夾下所有圖片文件的方法
- C#監(jiān)控文件夾變化的方法
- C#遞歸實(shí)現(xiàn)顯示文件夾及所有文件并計(jì)算其大小的方法
- C#實(shí)現(xiàn)判斷文件夾存在與否并創(chuàng)建文件夾的方法
相關(guān)文章
C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁(yè)信息實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁(yè)信息實(shí)現(xiàn)方法,涉及C#基于會(huì)話操作登陸網(wǎng)頁(yè)及頁(yè)面讀取相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
C# WinForm國(guó)際化實(shí)現(xiàn)的簡(jiǎn)單方法
這篇文章主要介紹了C# WinForm國(guó)際化實(shí)現(xiàn)的簡(jiǎn)單方法,有需要的朋友可以參考一下2014-01-01
C#單例模式(Singleton Pattern)實(shí)例教程
這篇文章主要介紹了C#單例模式(Singleton Pattern)的實(shí)現(xiàn)方法,主要講述了即時(shí)加載的單例模式、延遲加載的單例模式與線程安全的單例模式,需要的朋友可以參考下2014-09-09

