问题描述
我无法在Internet解决方案中找到如何使用HttpPostedFileBase在文件中附加或附加字符串。
例如,我使用HttpPostedFileBase获取此图像文件:
false
我想连接一个字符串:
hello.jpg
这将帮助我防止使用ASP.NET MVC在服务器中上传具有相同名称的图像。
这是我的代码,非常简单:
hello00001.jpg
我尝试过:
HttpPostedFileBase archivo = Request.Files["Image"];
if (archivo != null && archivo.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/Images"),Path.GetFileName(archivo.FileName));
archivo.SaveAs(path);
}
但是给我这个:
var path = Path.Combine(Server.MapPath("~/Images"),Path.GetFileName(archivo.FileName) + "00001");
也尝试过这个:
hello.jpg00001
也给我这个:
archivo.SaveAs(path + "00001");
我的问题看起来很简单,但是我不知道该怎么做。
解决方法
您可以尝试这个;
fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName); // hello
fileName+="00001";
fileExtension = System.IO.Path.GetExtension(file.FileName); // jpg
string path = System.IO.Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads"),$"{fileName}{fileExtension}"); // ~/Uploads/hello00001.jpg
file.SaveAs(path);