0

这是我尝试过的,请注意lblImageAlt.Text属性已设置为'Images/'

        string ImgPath1 = lblImageAlt1.Text.ToString();
        string ImgPath2 = lblImageAlt2.Text.ToString();
        string ImgPath3 = lblImageAlt3.Text.ToString();

        string filename1 = "";
        string filename2 = "";
        string filename3 = "";


        if (fileuploadimages1.HasFile)
        {
            if (File.Exists(Server.MapPath(ImgPath1 + filename1)))
            {
                string extension = Path.GetExtension(filename1);
                string name = Path.GetFileNameWithoutExtension(filename1);
                int fileMatchCount = 1;
                while (File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
                    fileMatchCount++;

                fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
            }
            else
            {
                fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
            }
        }
        else
        {
            filename1 = "noImage.jpg";
        }

但相同的图像没有附加数字。我在这里做错了什么?

4

3 回答 3

1

您实际上并没有修改 filename1。您正在检查它是否以 (0)、(1) 等结尾并增加索引,但从未实际修改变量。

于 2013-05-28T19:58:10.607 回答
1

Path.GetFileName 返回带有扩展名的整个文件名。
因此,您的代码正在检查是否存在具有某些名称的文件,例如

 image.jpg1

您应该更改代码以将文件名拆分为基本文件名和扩展名,检查文件名是否存在,然后从其组件中重建文件名并添加增量编号,直到找到不存在的文件名

// Extract just the filename from the posted file removing the path part (image.jpg)
filename1 = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
baseFile = Path.GetFileNameWithoutExtension(fileuploadimages1.PostedFile.FileName);
extension = Path.GetExtension(fileuploadimages1.PostedFile.FileName);
int fileMatchCount = 1;

// Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
while(File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1)))
{
    // This will create a filename like 'image(001).jpg'
    fileName1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
    fileMatchCount++;
}
// Existing the loop with a name that should not exist in the destination folder
fileuploadimages1.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1));
于 2013-05-28T19:58:56.450 回答
1

尝试使用

    if(File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
    string extension = Path.GetExtension(filename1);
    string name = Path.GetFileNameWithoutExtension(filename1);
    int fileMatchCount = 1;
    while(File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
        fileMatchCount++;

    fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
    fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
于 2013-05-28T20:01:49.230 回答