如果文件全部存在,如何创建新文件夹? [英] How to create new folder if file is allread present ?

查看:156
本文介绍了如果文件全部存在,如何创建新文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在上传图片,但是如果某个图片同名,那么图片覆盖... !!那我该怎么办?

我可能需要创建新文件夹才能存储此图像吗?或者其他可能解决方案?



如果我必须创建新文件夹,那么这个怎么可能我要编写什么代码?



我尝试过:



[HttpPost]

公共ActionResult索引(上传上传,HttpPostedFileBase文件)

{



if(File == null)

{

ModelState .AddModelError(customeerror,请上传你的文件);

}





try

{

//字符串文件名= Guid.NewGuid()+ Path.GetExtension(File.FileName);

string filename = Path.GetFileName (File.FileName);

File.SaveAs(Path.Combine(Server.MapPath(〜/ uploadcv),filename));

using(NGOEntities1 db =新的NGOEntities1())

{

upload.resum e =文件名;

db.uploads.Add(上传);

db.SaveChanges();

}

ModelState.Clear();

upload = null;

ViewBag.message =Succcess;





}

catch(例外情况)

{

ViewBag.message =错误;

返回查看();

}

返回RedirectToAction(list);

}

i am uploading image but if some image with same name then image override ...!! so what can i do ??
may i have to create new folder to store this image ? or what other possibly solution ??

if i have to create new folder then how this posible what code i have to write ??

What I have tried:

[HttpPost]
public ActionResult Index(upload upload,HttpPostedFileBase File)
{

if (File == null)
{
ModelState.AddModelError("customeerror", "Please Upload Your file");
}


try
{
// string filename = Guid.NewGuid() + Path.GetExtension(File.FileName);
string filename = Path.GetFileName(File.FileName);
File.SaveAs(Path.Combine(Server.MapPath("~/uploadcv"), filename));
using (NGOEntities1 db = new NGOEntities1())
{
upload.resume = filename;
db.uploads.Add(upload);
db.SaveChanges();
}
ModelState.Clear();
upload = null;
ViewBag.message = "Succcess";


}
catch(Exception Ex)
{
ViewBag.message = "Error";
return View();
}
return RedirectToAction("list");
}

推荐答案

使用 File.Exists [ ^ ]查看文件是否已存在,如果它确实改变它就像在最后添加一个数字,然后再次检查,依此类推,直到你提交一个不存在的文件。



承担考虑到人们同时上传,你可能想要围绕这段代码实现锁定。
Use File.Exists[^] to see if the file already exists, and if it does alter it like adding a number to the end, then checking again and so on until you file a file that doesn't exist.

Bear in mind people uploading at the same time though, you might want to implement locking around this code.


这篇关于如果文件全部存在,如何创建新文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆