一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net C#文件操作(追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件)

时间:2011-04-22 编辑:简简单单 来源:一聚教程网

asp教程.net c#文件操作(追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件)
c#追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件、指定文件夹下 面的所有内容copy到目标文件夹下面、指定文件夹下面的所有内容detele、读取文本文件、获取文件列表、读取日志文件、写入日志文件、创建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#移动文件
string orignfile,newfile;
orignfile = server.mappath(".")+"mytext.txt";
newfile = server.mappath(".")+"mytextcopy.txt";
file.move(orignfile,newfile);
c#创建目录
// 创建目录c:sixage
directoryinfo d=directory.createdirectory("c:sixage");
// d1指向c:sixagesixage1
directoryinfo d1=d.createsubdirectory("sixage1");
// d2指向c:sixagesixage1sixage1_1
directoryinfo d2=d1.createsubdirectory("sixage1_1");
// 将当前目录设为c:sixage
directory.setcurrentdirectory("c:sixage");
// 创建目录c:sixagesixage2
directory.createdirectory("sixage2");
// 创建目录c:sixagesixage2sixage2_1
directory.createdirectory("sixage2sixage2_1");
递归删除文件夹及文件
<%@ page language=c#%>
<%@ import namespace="system.io"%>

public void deletefolder(string dir)
{
if (directory.exists(dir)) //如果存在这个文件夹删除之
{
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:gbook11";
deletefolder(dir); //调用函数删除文件夹
}

// ======================================================
// 实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面
// 如果目标文件夹为只读属性就会报错。
// april 18april2005 in stu
// ======================================================
public static void copydir(string srcpath,string aimpath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if(aimpath[aimpath.length-1] != path.directoryseparatorchar)
aimpath += path.directoryseparatorchar;
// 判断目标目录是否存在如果不存在则新建之
if(!directory.exists(aimpath)) directory.createdirectory(aimpath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
// string[] filelist = directory.getfiles(srcpath);
string[] filelist = directory.getfilesystementries(srcpath);
// 遍历所有的文件和目录
foreach(string file in filelist)
{
// 先当作目录处理如果存在这个目录就递归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());
}
}
// ======================================================
// 实现一个静态方法将指定文件夹下面的所有内容detele
// 测试的时候要小心操作,删除之后无法恢复。
// ======================================================
public static void deletedir(string aimpath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if(aimpath[aimpath.length-1] != path.directoryseparatorchar)
aimpath += path.directoryseparatorchar;
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
// 如果你指向delete目标文件下面的文件而不包含目录请使用下面的方法
// string[] filelist = directory.getfiles(aimpath);
string[] filelist = directory.getfilesystementries(aimpath);
// 遍历所有的文件和目录
foreach(string file in filelist)
{
// 先当作目录处理如果存在这个目录就递归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;
/**////

///


///
///
//--------------------------------------------------
//---------------------------------------------------
public static void copyfolder(string strfrompath,string strtopath)
{
//如果源文件夹不存在,则创建
if (!directory.exists(strfrompath))
{
directory.createdirectory(strfrompath);
}
//取得要拷贝的文件夹名
string strfoldername = strfrompath.substring(strfrompath.lastindexof("") + 1,strfrompath.length - strfrompath.lastindexof("") - 1);
//如果目标文件夹中没有源文件夹则在目标文件夹中创建源文件夹
if (!directory.exists(strtopath + "" + strfoldername))
{
directory.createdirectory(strtopath + "" + strfoldername);
}
//创建数组保存源文件夹下的文件名
string[] strfiles = directory.getfiles(strfrompath);
//循环拷贝文件
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);
}

//创建directoryinfo实例
directoryinfo dirinfo = new directoryinfo(strfrompath);
//取得源文件夹下的所有子文件夹名称
directoryinfo[] zipath = dirinfo.getdirectories();
for (int j = 0;j < zipath.length;j++)
{
//获取所有子文件夹名
string strzipath = strfrompath + "" + zipath[j].tostring();
//把得到的子文件夹当成新的源文件夹,从头开始新一轮的拷贝
copyfolder(strzipath,strtopath + "" + strfoldername);
}
}
一.读取文本文件
 /**////


 /// 读取文本文件
 ///

 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("请选择文本文件");
  }
  else
  {
  streamreader filestream = new streamreader(txtfilepath,encoding.default);
  txtcontent.text = filestream.readtoend();
  filestream.close();
  }
  }
  }
二.获取文件列表
/**////
/// 获取文件列表
///

private void getfilelist()
{
string strcurdir,filename,fileext;

/**////文件大小
long filesize;

/**////最后修改时间;
datetime filemodify;

/**////初始化
if(!ispostback)
{
/**////初始化时,默认为当前页面所在的目录
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();

/**////动态添加单元格内容
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("最后修改时间"));
tr.cells.add(td);

tabledirinfo.rows.add(tr);

/**////针对当前目录建立目录引用对象
directoryinfo dirinfo = new directoryinfo(txtcurdir.text);

/**////循环判断当前目录下的文件和目录
foreach(filesysteminfo fsi in dirinfo.getfilesysteminfos())
{
filename = "";
fileext = "";
filesize = 0;

/**////如果是文件
if(fsi is fileinfo)
{
fi = (fileinfo)fsi;

/**////取得文件名
filename = fi.name;

/**////取得文件的扩展名
fileext = fi.extension;

/**////取得文件的大小
filesize = fi.length;

/**////取得文件的最后修改时间
filemodify = fi.lastwritetime;
}

/**////否则是目录
else
{
dir = (directoryinfo)fsi;

/**////取得目录名
filename = dir.name;

/**////取得目录的最后修改时间
filemodify = dir.lastwritetime;

/**////设置文件的扩展名为"文件夹"
fileext = "文件夹";
}

/**////动态添加表格内容
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()+"字节"));
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);
}
}
三.读取日志文件
/**////


/// 读取日志文件
///

private void readlogfile()
{
/**////从指定的目录以打开或者创建的形式读取日志文件
filestream fs = new filestream(server.mappath("upedfile")+"logfile.txt", filemode.openorcreate, fileaccess.read);

/**////定义输出字符串
stringbuilder output = new stringbuilder();

/**////初始化该字符串的长度为0
output.length = 0;

/**////为上面创建的文件流创建读取数据流
streamreader read = new streamreader(fs);

/**////设置当前流的起始位置为文件流的起始点
read.basestream.seek(0, seekorigin.begin);

/**////读取文件
while (read.peek() > -1)
{
/**////取文件的一行内容并换行
output.append(read.readline() + "n");
}

/**////关闭释放读数据流
read.close();

/**////返回读到的日志文件内容
return output.tostring();
}
四.写入日志文件

/**////


/// 写入日志文件
///

///
private void writelogfile(string input)
{
/**////指定日志文件的目录
string fname = server.mappath("upedfile") + "logfile.txt";
/**////定义文件信息对象
fileinfo finfo = new fileinfo(fname);

/**////判断文件是否存在以及是否大于2k
if ( finfo.exists && finfo.length > 2048 )
{
/**////删除该文件
finfo.delete();
}
/**////创建只写文件流
using(filestream fs = finfo.openwrite())
{
/**////根据上面创建的文件流创建写数据流
streamwriter w = new streamwriter(fs);

/**////设置写数据流的起始位置为文件流的末尾
w.basestream.seek(0, seekorigin.end);

w.write("nlog entry : ");

/**////写入当前系统时间并换行
w.write("{0} {1} rn",datetime.now.tolongtimestring(),datetime.now.tolongdatestring());

/**////写入日志内容并换行
w.write(input + "n");

/**////写入------------------------------------“并换行
w.write("------------------------------------n");

/**////清空缓冲区内容,并把缓冲区内容写入基础流
w.flush();

/**////关闭写数据流
w.close();
}
}
五.c#创建html文件
/**////


/// 创建html文件
///

private void createhtmlfile()
{
/**////定义和html标记数目一致的数组
string[] newcontent = new string[5];
stringbuilder strhtml = new stringbuilder();
try
{
/**////创建streamreader对象
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());
}
/**////为标记数组赋值
newcontent[0] = txttitle.text;//标题
newcontent[1] = "backcolor='#cccfff'";//背景色
newcontent[2] = "#ff0000";//字体颜色
newcontent[3] = "100px";//字体大小
newcontent[4] = txtcontent.text;//主要内容

/**////根据上面新的内容生成html文件
try
{
/**////指定要生成的html文件
string fname = server.mappath("createhtml") +"" + datetime.now.tostring("yyyymmddhhmmss") + ".html";

/**////替换html模版文件里的标记为新的内容
for(int i=0;i < 5;i++)
{
strhtml.replace("$htmlkey["+i+"]",newcontent[i]);
}
/**////创建文件信息对象
fileinfo finfo = new fileinfo(fname);

/**////以打开或者写入的形式创建文件流
using(filestream fs = finfo.openwrite())
{
/**////根据上面创建的文件流创建写数据流
streamwriter sw = new streamwriter(fs,system.text.encoding.getencoding("gb2312"));

/**////把新的内容写到创建的html页面中
sw.writeline(strhtml);
sw.flush();
sw.close();
}

/**////设置超级链接的属性
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 {}
}
}

 

热门栏目