如何验证重复的名称文件上传 [英] how to validate duplicate name file upload

查看:120
本文介绍了如何验证重复的名称文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友

我想把文件上传到我的项目文件夹(.. \TextFiles\Blogs)。

但我想通过独特的方式上传文件名称,以便可以上传两个同名的文件

,也可以覆盖现有文件。

我的代码如下:

Hello Friends
I want to upload a file into my projects Folder(..\TextFiles\Blogs).
But I want to upload files by unique name so that niether two files with same name
can be uploaded nor override the existing file.
My Code is as below:

protected void blgBtn_Click(object sender, EventArgs e)
       {

           string fileName = blgFile.FileName;
           string filePath = blgFile.PostedFile.FileName;
           int fileLength = blgFile.PostedFile.ContentLength;
           blgFile.SaveAs(Server.MapPath("~/TextFiles/Blogs") + fileName);
           byte[] imageBytes = new byte[fileLength];
           blgFile.PostedFile.InputStream.Read(imageBytes, 0, fileLength);

           if (System.IO.File.Exists(filePath))
           {
               int counter = 2;
               while (System.IO.File.Exists(filePath))
               {
                   // if a file with this name already exists,
                   // prefix the filename with a number.
                   string tempfileName = counter.ToString() + fileName;
                   filePath = filePath + tempfileName;
                   counter++;
               }


               cmd = new SqlCommand("AddImg", con);
               cmd.CommandType = CommandType.StoredProcedure;
               SqlParameter[] prms = new SqlParameter[5];
               //cmd.Parameters.AddWithValue("BlogName",blgTb.Text);
               cmd.Parameters.AddWithValue("BlogPath", blgFile.ToString());
               //cmd.Parameters.AddWithValue("BlogFile",imageBytes);
               cmd.Parameters.AddWithValue("Sequence", int.Parse(Seq.Text));
               cmd.Parameters.AddWithValue("Page", int.Parse(blgPage.Text));
               cmd.Parameters.AddWithValue("Date", DateTime.Parse(dtpCalendar.Text));
               cmd.Parameters.AddWithValue("Comment", blgComment.Text);
               con.Open();
               cmd.ExecuteNonQuery();
               con.Close();





如果不行则建议我写代码。



在此先感谢



最诚挚的问候

Akhilesh Pathak



If it not fine then suggest me write code.

Thanks in Advance

With Best Regards
Akhilesh Pathak

推荐答案

你已经使用了File.Exists方法

u have use File.Exists method
using System.IO;
string FileChk = Server.MapPath("~/TextFiles/Blogs") + fileName;
if (File.Exists(FileChk ))
{
   //then file is exist

}


这篇关于如何验证重复的名称文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆