1. 程式人生 > 其它 >C#判斷檔案和資料夾是否存在 不存在則建立

C#判斷檔案和資料夾是否存在 不存在則建立

using System.IO;
string path = @"D:\accountDaoRu\";
        if (Directory.Exists(path) == false)
        {
            Directory.CreateDirectory(path);
        }

if (Directory.Exists(Server.MapPath(~/upimg/hufu)) == false)//如果不存在就建立file資料夾{
Directory.CreateDirectory(Server.MapPath(~/upimg/hufu));}
//Directory.Delete(Server.MapPath(~/upimg/hufu), true);
//刪除資料夾以及資料夾中的子目錄,檔案 //判斷檔案的存在 if (File.Exists(Server.MapPath(~/upimg/Data.html))){ Response.Write(Yes);//存在檔案}else{ Response.Write(No); //不存在檔案 File.Create(MapPath(~/upimg/Data.html));//建立該檔案} string name = GetFiles.FileName;//獲取已上傳檔案的名字 string size = GetFiles.PostedFile.ContentLength.ToString();//獲取已上傳檔案的大小 string type = GetFiles.PostedFile.ContentType;//
獲取已上傳檔案的MIME string postfix = name.Substring(name.LastIndexOf(.) + 1);//獲取已上傳檔案的字尾 string ipath = Server.MapPath(upimg) +\\+ name;//獲取檔案的實際路徑 string fpath = Server.MapPath(upfile) + \\ + name; string dpath = upimg\\ + name;//判斷寫入資料庫的虛擬路徑 ShowPic.Visible = true;//啟用 ShowText.Visible = true;//啟用 //判斷檔案格式 if (name == ) { Response.Write(
<scriptalert('上傳檔案不能為空')</script);}else{ if (postfix == jpg || postfix == gif || postfix == bmp || postfix == png){ GetFiles.SaveAs(ipath); ShowPic.ImageUrl = dpath; ShowText.Text = 你上傳的圖片名稱是: + name + + 檔案大小: + size + KB + + 檔案型別: + type + + 存放的實際路徑為: + ipath;}else{ ShowPic.Visible = false;//隱藏圖片 GetFiles.SaveAs(fpath);//由於不是圖片檔案,因此轉存在upfile這個資料夾 ShowText.Text = 你上傳的檔名稱是: + name + + 檔案大小: + size + KB + + 檔案型別: + type + + 存放的實際路徑為: + fpath;}