完成文件的上传和删除功能

此博客展示了使用C#实现文件上传和删除功能的代码。定义了UPFILE类,包含上传控件、存储路径、文件大小和格式等属性,实现了上传文件、显示文件名和路径、删除文件等方法,还对文件格式、大小和重名情况进行了判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Web;
using System.IO;
using System.Text;

namespace USTC
{
 ///  /// upfile类完成文件的上传和删除功能
 ///
 public class UPFILE
 {
  private System.Web.HttpPostedFile postedFile=null;
  private string savePath="";
  private string extension="";
  private int fileLength=0;
  //上传控件
  public System.Web.HttpPostedFile PostedFile  
  {
   get    {     return postedFile;    }
   set    {     postedFile=value;    }
  }

  //存储路径
  public string SavePath  
  {
   get   
   {
    if(savePath!="")
        return savePath;     return "C://";    }
   set    {     savePath=value;    }  
  }

  //文件大小
  public int FileLength  
  {
   get   
   {
    if(fileLength!=0)
       {     return fileLength;     }
    return 1024;    }
   set    {     fileLength=value*1024;    }

  }

  //文件格式
  public string Extension  
  {
   get   
   {
    if(extension!="")
       {      return extension;     }
    return "";    }
   set    {     extension=value;    }

  }

  public string PathToName(string path)
  {
    int pos=path.LastIndexOf("//");//找到路径的最后一个“/”分割符,
   return path.Substring(pos+1);   }//得到这个路径下的文件名

  //上传文件
  public string Upload()
  {
    if(PostedFile!=null)
    {
      try   
       {
        string fileName=PathToName(PostedFile.FileName);
        if(!fileName.EndsWith(Extension))
        {      return "你必须选择 "+Extension+" 这个格式的文件!";      }
        if(PostedFile.ContentLength>FileLength)
        {      return "文件太大!";      }
        if(File.Exists((SavePath+"//"+fileName)))
        {      return "文件名重复!";      }
        else    
        {
         PostedFile.SaveAs(SavePath+"//"+fileName);
         return "上传文件成功!";      }   
       }
       catch(System.Exception exc)
       {     return exc.Message;    }   
    }
   return "请选择文件上传!";   }

  //显示文件名
  public string upfilename()
  {
    string fileName=PathToName(PostedFile.FileName);
   return fileName;  }

  //显示详细路径
  public string url() 
  {
   string fileName=PathToName(PostedFile.FileName);
   string urls=SavePath+"//"+fileName;
   return urls;  }

  //删除上传的文件
  public string delete(string url) 
  {
   try   
   {
    File.Delete(url);
    return "删除文件成功!";          }
   catch(System.Exception exc)
   {     return exc.Message;    }
  }


 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值