上传遍历文件夹的上传文件(本机测试)

using System;
using System.Collections.Generic;
using System.Web;
using System.IO;

/// <summary>
///FileStreamUpload 的摘要说明
/// </summary>
public class FileStreamUpload
{
 public FileStreamUpload()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }

 public static string FileDirectoryUpload(string path)
{
string fileAndPath = "上传成功!";
try
{
DirectoryInfo info = new DirectoryInfo(path);

if (!info.Exists || info == null)
fileAndPath= "文件夹为空!";

FileSystemInfo[] files = info.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
FileUpload(file.FullName);
//对于子目录,进行递归调用
else
FileDirectoryUpload(files[i].FullName);
}

return fileAndPath;
}
catch (Exception ex)
{
return ex.Message;
}

}


    /// <summary>
    /// 根据路径,使用FileStream上传文件
    /// </summary>
    /// <param name="filePath"></param>
    /// <returns></returns>
    private static string FileUpload(string filePath)
    {
        string result = "";
        string filename = "";
        FileInfo file = new FileInfo(filePath);
        string fileExtenName = file.Extension;
        //string fileNewName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtenName;
        int ipos = filePath.LastIndexOf("\\");
        if (ipos.ToString() != "-1")
        {
            filename = filePath.Substring(ipos);
        }
        else
        {
            filename = filePath;
        }
        string aFirstName = filename.Substring(filename.LastIndexOf("\\") + 1, (filename.LastIndexOf(".") - filename.LastIndexOf("\\") - 1)) + file.Extension;
        string fileSavePath = System.Web.HttpContext.Current.Server.MapPath(@"~\Upload\") + aFirstName;
        ///真正上传,从这里开始
        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
        //把文件流中转化成字节数组  
        byte[] imageBytes = new byte[(int)fs.Length];
        fs.Read(imageBytes, 0, imageBytes.Length);
        fs.Close();
        MemoryStream ms = new MemoryStream(imageBytes);
        //定义并实例化一个内存流,以存放提交上来的字节数组。  
        FileStream fss = new FileStream(fileSavePath, FileMode.Create);
        ms.WriteTo(fss);
        fss.Close();
        ms.Close();
        return result = "Upload/" + aFirstName;

    }

  }

转载于:https://www.cnblogs.com/iWorld/archive/2012/10/25/2739270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值