C#文件目录操作完全手册

发表于:2016-4-27 10:18

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:jerrylsxu    来源:51Testing软件测试网采编

  需要 using System.IO;
  1) 相对路径转绝对路径
  string fullfolder = HttpContext.Current.Server.MapPath(folder);
  2) 文件移动(改名)
  File.Move(Server.MapPath("/a.txt"), Server.MapPath("/b.txt"));
  3) 文件复制
  File.Copy(Server.MapPath("/a.txt"), Server.MapPath("/b.txt"), true);
  4) 文件是否存在
  File.Exists(filefullname)
  5) 目录是否存在
  Directory.Exists(fullfolder))
  6) 创建目录
  Directory.CreateDirectory(fullfolder);
  7) 目录移动
  Directory.Move
  8) 读取文本文件
  StreamReader srd = File.OpenText(fullfilename);
  srd.ReadToEnd();
  srd.Close();
  srd.Dispose();
  9) 写文件
  StreamWriter swr = File.CreateText(Server.MapPath("test.txt"));
  swr.Write("message");
  swr.Close();
  swr.Dispose();
  10)删除文件
// 删除硬盘上的文件
if (File.Exists(filefullname))
{
File.Delete(filefullname);
}
  11)目录遍历
public void ListFiles(string pathname)
{
// 所有目录与文件
string[] subDirs = Directory.GetDirectories(pathname);
string[] subFiles = Directory.GetFiles(pathname);
foreach (string subDir in subDirs)
{
ListFiles(subDir);
}
// 所有文件
foreach (string subFile in subFiles)
{
string filename = Path.GetFileName(subFile);
}
}
  12)文件修改时间
  FileInfo fi = new FileInfo(@"c:\test.txt");
  DateTime writetime = fi.LastWriteTime;
  13)从含路径的文件名中提取文件名
  System.IO.Path.GetFileName(fullPath);//文件名
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号