C#获取程序路径
string path1 = AppDomain.CurrentDomain.BaseDirectory; string path2 = Environment.CurrentDirectory; Console.WriteLine(path1); Console.WriteLine(path2);
输出结果
判断文件是否存在 不存在创建
string path = AppDomain.CurrentDomain.BaseDirectory+ "test.txt"; if (!File.Exists(path)) { //判断文件是否存在 不存在创建 FileStream fs = new FileStream(path, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.WriteLine("456"); sw.Close(); }
创建文件夹
string picPath = AppDomain.CurrentDomain.BaseDirectory + "/pic"; string picPath1 = AppDomain.CurrentDomain.BaseDirectory + "/pic/pic1"; string picPath2 = AppDomain.CurrentDomain.BaseDirectory + "/pic/pic2"; string picPath3 = AppDomain.CurrentDomain.BaseDirectory + "/pic/pic3"; if (!File.Exists(picPath)) { Directory.CreateDirectory(picPath); } if (!File.Exists(picPath1)) { Directory.CreateDirectory(picPath1); } if (!File.Exists(picPath2)) { Directory.CreateDirectory(picPath2); } if (!File.Exists(picPath3)) { Directory.CreateDirectory(picPath3); }
遍历该文件夹下的所有文件
string picPath = AppDomain.CurrentDomain.BaseDirectory + "/pic"; DirectoryInfo dir = new DirectoryInfo(picPath); DirectoryInfo[] dirinfo = dir.GetDirectories(); for (int i = 0; i < dirinfo.Length; i++) { Console.WriteLine(dirinfo[i].FullName); }