文件夹,文件这是常见的,怎么创建?要不要先判断是否存在?非常非常基础的知识点。
代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace dazilianxi.wenjian { public class WenJianLei { const string main_Dir = @"D:/WenTest"; const string wenjianpath = @"D:WenTestsecond.txt"; //根据文件夹全路径创建文件夹 public static void CreateDir(string subdir) { string path = main_Dir + "/" + subdir; if (Directory.Exists(path)) { Console.WriteLine("此文件夹已经存在,无需创建!"); } else { Directory.CreateDirectory(path); Console.WriteLine(path+" 创建成功!"); } } //根据文件夹名称创建文件夹 public static void CreateNameDir(string name) { if(name.Length!=0) { CreateDir(name); } else { Console.WriteLine("必须指定文件夹名称,才能创建!"); } } public static void CreateWenJian() { if (!File.Exists(wenjianpath)) { Console.WriteLine("文件创建成功!"); TextWriter tw = new StreamWriter(wenjianpath); tw.WriteLine("创建完文件加的第一行~~"); tw.Close(); } else { TextWriter tw = new StreamWriter(wenjianpath,true); tw.WriteLine("已经存在文件,再加一行吧~~"); tw.Close(); } } //文件大小计算 public static void CreateMoreSize() { long size = GetDirectoryLength(@"D:WenTest"); if (!File.Exists(wenjianpath)) { if (size <= 1) { TextWriter tw = new StreamWriter(wenjianpath); tw.WriteLine("创建完文件加的第一行~~"); tw.Close(); } else { Console.WriteLine("无法创建,已经超过限定大小了~~"); } } else { TextWriter tw = new StreamWriter(wenjianpath, true); tw.WriteLine("已经存在文件,再加一行吧~~"); tw.Close(); } } public static long GetDirectoryLength(string path) { if (!Directory.Exists(path)) { return 0; } long size = 0; //遍历指定路径下的所有文件 DirectoryInfo di = new DirectoryInfo(path); foreach (FileInfo fi in di.GetFiles()) { size += fi.Length; } //遍历指定路径下的所有文件夹 DirectoryInfo[] dis = di.GetDirectories(); if (dis.Length > 0) { for (int i = 0; i < dis.Length; i++) { size += GetDirectoryLength(dis[i].FullName); } } return size; } } }
调用代码
// wenjian.WenJianLei.CreateNameDir("mytest1"); //wenjian.WenJianLei.CreateWenJian(); wenjian.WenJianLei.CreateMoreSize();
来源:http://www.cnblogs.com/darrenji/p/3652062.html
http://www.cnblogs.com/hqbhonker/p/3494042.html