C# 上传文件

来源:互联网 发布:淘宝迪奥正品店 编辑:程序博客网 时间:2024/06/13 13:41

using System;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.IO;


//拷贝一份想要上传的文件放到指定的程序目录下
public string UploadFile()  //返回上传的文件名  包含路径
{
 OpenFileDialog ofd = new OpenFileDialog();
 ofd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
 ofd.Title = "选择你要上传的文件";
 ofd.ShowDialog();
 if (ofd.FileName.Length > 0)
 {
  string path = System.Windows.Forms.Application.ExecutablePath;
  FileInfo exeInfo = new FileInfo(path);
  path = exeInfo.DirectoryName + "\\";   //程序根目录
  string tempExcel = path + "user data\\temp\\"+ ofd.FileName.Split(new Char[] { '\\' }).Last();  //上传后保存在程序目录下的文件名
  if (File.Exists(tempExcel))
  {
   string just_name = ofd.FileName.Split(new Char[] { '\\' }).Last();  //不包含路径的文件名
   DialogResult result = MessageBox.Show(just_name + "已经存在,确认覆盖?", "文件上传提示", MessageBoxButtons.OKCancel);
   if (result == DialogResult.OK)
   {
    File.Copy(ofd.FileName, tempExcel, true);
    return ofd.FileName;
   }else{
    return "未选择文件!";
   }
  }else{
   File.Copy(ofd.FileName, tempExcel, true);
   return ofd.FileName;
  }
 }else{
  return "未选择文件!";
 }
}

0 0
原创粉丝点击