简体   繁体   English

如果 C# 中的文件夹中存在文件名更改

[英]File name change if exists in a folder in C#

In my application I need to save a file(image,pdf,txt) to a folder.在我的应用程序中,我需要将文件(图像,pdf,txt)保存到文件夹中。 I need to add as many images or files to my folder.我需要将尽可能多的图像或文件添加到我的文件夹中。 Suppose I have an image with name "image1", if this already exists in the folder and if another user trying to add another image with the name "image1" then my application automatically needs to change imagename to "image2".假设我有一个名称为“image1”的图像,如果该图像已存在于文件夹中,并且如果另一个用户尝试添加另一个名称为“image1”的图像,那么我的应用程序自动需要将图像名称更改为“image2”。 So the application should check whether the file exist, if so save the new image with a different name.所以应用程序应该检查文件是否存在,如果存在,用不同的名称保存新图像。 Any help will be appreciated.任何帮助将不胜感激。

Use the File.Exists method to determine the presence of a file.使用File.Exists方法确定文件是否存在。

However, it must be noted that conflict could still occur.但是,必须注意,冲突仍然可能发生。 For instance, there is a race condition in that the file could potentially be saved by someone else after the call to determine existence, yet before your call to create the file, so you will still need to account for error.例如,存在竞争条件,即文件可能在调用确定存在之后被其他人保存,但您调用创建文件之前,因此您仍然需要考虑错误。

What you might consider is giving each saved (uploaded?) file a unique name, and referencing them in a database - you can use Guid.NewGuid quite reliably in this case.您可能会考虑为每个保存的(上传的?)文件指定一个唯一的名称,并在数据库中引用它们——在这种情况下,您可以非常可靠地使用Guid.NewGuid

As for actually saving the file, you have numerous options here: you could use a FileStream , static methods exposed by the File class, or method of the FileUpload control if you're using that.至于实际保存文件,您有很多选择:您可以使用FileStream 、 static File class 公开的方法,或者如果您正在使用FileUpload控件的方法。 Please clarify your circumstances.请说明你的情况。

Lastly, depending on there size, and if a database is being used anyway, you might want to consider storing them as binary data in there, then name conflicts may be irrelevant.最后,取决于那里的大小,并且如果无论如何都在使用数据库,您可能需要考虑将它们作为二进制数据存储在那里,那么名称冲突可能是无关紧要的。

Of course, you can check if the file exists with System.IO.File.Exists(...) , but I think your requirements might be a bit too optimistic... there are multiple cases which you should consider.当然,您可以使用System.IO.File.Exists(...)检查文件是否存在,但我认为您的要求可能有点过于乐观......您应该考虑多种情况。 Suppose that you have:假设您有:

upload.extension
upload1.extension
upload01.extension
upload001.extension

The names above suggest that you should have some naming convention, but that naming convention is not going to be universal (unless you want to have a bunch of naming conventions to cover all of those cases).上面的名称表明您应该有一些命名约定,但该命名约定不会是通用的(除非您希望有一堆命名约定来涵盖所有这些情况)。 If the user wants to save a file named "upload" and your naming convention states that the file name would be incremented with a digit with no leading numbers, then you would try "upload1" and if that's not available then "upload2" until you find one that's available.如果用户想要保存一个名为“upload”的文件,并且您的命名约定表明文件名将增加一个没有前导数字的数字,那么您将尝试“upload1”,如果不可用,则使用“upload2”,直到您找到一个可用的。

Let's take the simple case with the convention of adding a digit with no leading zeroes:让我们用一个简单的例子来添加一个不带前导零的数字:

int i = 0
string fileExtension = ".extension";
string availableFileName = fileName;
while(System.IO.File.Exists(availableFileName+fileExtension))
{
    availableFileName = fileName + i;
    i++;
}
fileUpload.SaveAs(availableFileName+fileExtension);

This would append an integer at the end of the file name until you find a file name that is not duplicated.这将 append 和 integer 放在文件名的末尾,直到找到不重复的文件名。

You should be able to check if the file name already exists using System.IO.File.Exists ...您应该能够使用System.IO.File.Exists来检查文件名是否已经存在...

if(System.IO.File.Exists("image1")){
  //Use a different name
}

Of course you would need to refine this example to be more flexible for your specific needs.当然,您需要改进此示例以更灵活地满足您的特定需求。

You can do like...你可以这样做...

 if (System.IO.File.Exists("Path"))
    {
        fileUpload1.SaveAs("Path + New FileName");
    }

However it would be better if you save the file with appending Current DataTime with the filename.但是,如果您保存文件并在文件名中附加 Current DataTime 会更好。 eg例如

fileUpload1.SaveAs("Path + Orginal FileName" + DateTime.Now.ToString("yyyy-MM-dd HHmmtt") + "File Extension";

You can check for a file's existence with the System.IO.File.Exists [ MSDN ] method.您可以使用System.IO.File.Exists [ MSDN ]方法检查文件是否存在。 It takes a path string as its argument.它接受一个路径字符串作为它的参数。

For manipulating the path string should a file exist, take a look at System.IO.Path [ MSDN ] .要在文件存在时操作路径字符串,请查看System.IO.Path [ MSDN ] It's a great utility for doing just what you need.这是一个很好的实用程序,可以满足您的需要。

I've successfully solved this by having any uploaded files be named by GUID's string representation.我已经通过使用 GUID 的字符串表示来命名任何上传的文件成功地解决了这个问题。

If needed, you can maintain the mapping between GUID's generated file name and the original filename in the DB.如果需要,您可以维护 GUID 生成的文件名和数据库中原始文件名之间的映射。

Or just use this:或者只是使用这个:

    // 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;
}

Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx来源: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM