在我的应用程序中,我需要将文件(图像、pdf、txt)保存到一个文件夹中。我需要添加尽可能多的图像或文件到我的文件夹中。假设我有一个名为“image1”的图像,如果它已经存在于文件夹中,而另一个用户试图添加另一个名称为“image1”的图像,则我的应用程序自动需要将图像名称更改为“image2”。因此,应用程序应检查文件是否存在,如果存在,则使用不同的名称保存新图像。任何帮助都将不胜感激。
在我的应用程序中,我需要将文件(图像、pdf、txt)保存到一个文件夹中。我需要添加尽可能多的图像或文件到我的文件夹中。假设我有一个名为“image1”的图像,如果它已经存在于文件夹中,而另一个用户试图添加另一个名称为“image1”的图像,则我的应用程序自动需要将图像名称更改为“image2”。因此,应用程序应检查文件是否存在,如果存在,则使用不同的名称保存新图像。任何帮助都将不胜感激。
System.IO.File.Exists(...)
来检查文件是否存在,但我认为你的要求可能过于乐观了...有多种情况需要考虑。假设你有以下情况:upload.extension
upload1.extension
upload01.extension
upload001.extension
int i = 0
string fileExtension = ".extension";
string availableFileName = fileName;
while(System.IO.File.Exists(availableFileName+fileExtension))
{
availableFileName = fileName + i;
i++;
}
fileUpload.SaveAs(availableFileName+fileExtension);
File.Exists
方法来确定文件是否存在。Guid.NewGuid
。FileStream
、File
类公开的静态方法,或者如果您使用FileUpload
控件,则使用其方法。请澄清您的情况。您应该能够使用 System.IO.File.Exists
来检查文件名是否已存在...
if(System.IO.File.Exists("image1")){
//Use a different name
}
当然,您需要根据自己的具体需求对此示例进行更灵活的改进。
你可以这样做...
if (System.IO.File.Exists("Path"))
{
fileUpload1.SaveAs("Path + New FileName");
}
然而,如果您将当前日期和时间附加到文件名中保存文件,效果会更好。例如:
fileUpload1.SaveAs("Path + Orginal FileName" + DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + "File Extension";
我已经成功解决了这个问题,通过使用GUID的字符串表示来命名任何上传的文件。
如果需要,您可以在数据库中维护GUID生成的文件名与原始文件名之间的映射关系。
或者只需使用以下方法:
// Create a temporary file name to use for checking duplicates.
string tempfileName = "";
// Check to see if a file already exists with the
// same name as the file to upload.
if (System.IO.File.Exists(pathToCheck))
{
int counter = 2;
while (System.IO.File.Exists(pathToCheck))
{
// if a file with this name already exists,
// prefix the filename with a number.
tempfileName = counter.ToString() + fileName;
pathToCheck = savePath + tempfileName;
counter ++;
}
fileName = tempfileName;
}
来源:http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.fileupload.saveas.aspx