user3727052
user3727052

Reputation: 33

Files on the server are overwritten with files of the same name

I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?

here is y code to upload:

 protected void btnAddExpenditure_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {

           string FileName = FileUpload1.PostedFile.FileName;
           if (File.Exists(FileName))
            {
                FileName = Guid.NewGuid() + FileName;
            }
                //check file Extension & Size
            int filesize = FileUpload1.PostedFile.ContentLength;
            if (filesize > (20 * 1024))
            {
                Label1.Text = "Please upload a zip or a pdf file";
            }

            string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
            if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
            {
                Label1.ForeColor = System.Drawing.Color.Green;
                Label1.Text = "Please upload a zip or a pdf file";

            }



            else
            {
                string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);



                //save file to disk

                FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}

Upvotes: 0

Views: 75

Answers (1)

Carlos Rodriguez
Carlos Rodriguez

Reputation: 2220

string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
    FileName = Guid.NewGuid() + FileName;
}
...    

string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...

string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);

you're still using the original FileUpload1.PostedFile.FileName. This should be changed to

string ReceiptFileName = Path.GetFileName(FileName);

EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then

FileName = Guid.NewGuid() + FileName;

would result in something like 123-4321-GUIDC:\Folder\File.txt

I doubt that's what you want. You might want to flip that around

FileName = FileName + Guid.NewGuid();

Upvotes: 1

Related Questions