if(System.IO.File.Exists(@"")) { } if (System.IO.File.Exists(HttpRuntime.AppDomainAppPath + model.FilePath)) //判斷文件是否存在 { try { System.IO.File.Delete(HttpRuntime.AppDomainAppPath + model.FilePath); //刪除表中記錄 db.SaveChanges(); } catch (System.IO.IOException e) { } }
var path = Path.GetDirectoryName(filePath); 獲得文件路徑
var dir = path + "/" + docdeta[i].Column8.Substring(0, docdeta[i].Column8.LastIndexOf('.'))+ "_files"; FileAttributes attr = System.IO.File.GetAttributes(dir); //經過測試目錄不存在報異常, if (attr == FileAttributes.Directory) { Directory.Delete(path, true); //刪除目錄 } if (Directory.Exists(dir))//判斷是否存在 (用這個) { Directory.Delete(path, true); }
private void button1_Click(object sender, EventArgs e) { SaveTxt(@"C:\新建文件夾\123.txt"); } public void SaveTxt(string path) { #region --判斷目錄是否存在 //當目錄是@"C:\新建文件夾\123.txt" 創建123.txt文件夾 if (Directory.Exists(path) == false)//如果不存在就創建file文件夾 { Directory.CreateDirectory(path); } #endregion #region --如果文件存在,將覆蓋文件 //創建文件, 如果文件已存在,將被覆蓋 FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write); StreamWriter sw0 = new StreamWriter(fs1); sw0.WriteLine("123456");//開始寫入值 sw0.Close(); sw0.Dispose(); fs1.Close(); fs1.Dispose(); #endregion #region --文件不存創建,存在則追加 //文件不存在則創建,存在則追加追加內容 FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write); StreamWriter sr = new StreamWriter(fs); sr.WriteLine("0000000");//開始寫入值 sr.Close(); sr.Dispose(); fs.Close(); fs.Dispose(); #endregion #region --如果文件存在,將覆蓋文件 StreamWriter sw = new StreamWriter(path); sw.WriteLine("211321456"); sw.Flush(); // sw.Close(); sw.Dispose(); #endregion System.Diagnostics.Process.Start("explorer.exe", path.Substring(0, path.LastIndexOf("\\") + 1)); }