C#中对于文件的操作

string ChangeExtension=System.IO.Path.ChangeExtension(path,".old");//更改路径字符串的扩展名。
string CombinePath=System.IO.Path.Combine(@"c:/","b.txt");//合并两个路径字符串。
string DirectoryName=System.IO.Path.GetDirectoryName(path);//返回指定路径字符串的目录信息。
string Extension=System.IO.Path.GetExtension(path);//返回指定的路径字符串的扩展名。
string FileName=System.IO.Path.GetFileName(path);//返回指定路径字符串的文件名和扩展名。
string FileNameWithoutExtension=System.IO.Path.GetFileNameWithoutExtension(path); //返回不具有扩展名的指定路径字符串的文件名。
string FullPath=System.IO.Path.GetFullPath(path);//返回指定路径字符串的绝对路径。
string PathRoot=System.IO.Path.GetPathRoot(path);//获取指定路径的根目录信息。
string TempFileName=System.IO.Path.GetTempFileName();//返回唯一临时文件名并在磁盘上通过该名称创建零字节文件。
string TempPath=System.IO.Path.GetTempPath();//返回当前系统的临时文件夹的路径。
string HasExtension=System.IO.Path.HasExtension(path).ToString();//确定路径是否包括文件扩展名。
string IsPathRooted=System.IO.Path.IsPathRooted(path).ToString();//获取一个值,该值指示指定的路径字符串是包含绝对路径信息还是包含相对路径信息。 

 

获取某目录下的所有文件(包括子目录下文件)的数量#region 获取某目录下的所有文件(包括子目录下文件)的数量
public int GetFileNum(string Path)
{
int fileNum = 0;
string[] fileList = System.IO.Directory.GetFileSystemEntries(Path);
// 遍历所有的文件和目录
foreach(string file in fileList)
{
if(System.IO.Directory.Exists(file))
GetFileNum(file);
else
fileNum++;
}
return fileNum;
}
#endregion

获取某目录下的所有文件(包括子目录下文件)的大小#region 获取某目录下的所有文件(包括子目录下文件)的大小
public long GetDirectoryLength(string dirPath)
{
if(!Directory.Exists(dirPath))
return 0;
long len=0;
DirectoryInfo di=new DirectoryInfo(dirPath);
foreach(FileInfo fi in di.GetFiles())
{
len+=fi.Length;
}
DirectoryInfo[] dis=di.GetDirectories();
if(dis.Length>0)
{
for(int i=0;i<dis.Length;i++)
{
len+=GetDirectoryLength(dis[i].FullName);
}
}
return len;
}
#endregion

读取文件#region 读取文件
private string file_get_contents(string path)
{
StringBuilder s=new StringBuilder();
using (StreamReader sr = new StreamReader(path,System.Text.Encoding.GetEncoding ("GB2312")))
{
string line;
while ((line = sr.ReadLine()) != null)
{
s.Append(line);
}
}
return s.ToString();
}
#endregion

写文件#region 写文件
public static void writefile()
{
StreamWriter sw = new StreamWriter("TestFile.txt",true,System.Text.Encoding.GetEncoding("GB2312")) ;
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值