写法1、
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("/Upload/");
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fis = di.GetFiles();
foreach (FileInfo fi in fis)
{
//OPM-293 CD03 DPM 成品检定报告 13021402.pdf
string a1 = fi.Name.Substring(0, fi.Name.IndexOf("成品检定报告")).Trim();//OPM-293 CD03
string a2 = fi.Name.Substring(fi.Name.IndexOf("告") + 1).Trim().Replace(".pdf", "");//13021402
string a3 = fi.Name;
//新建一个文件夹
string imgpath = System.Web.HttpContext.Current.Server.MapPath("/Upload1/" + a1 + " " + a2 + "/");//上传路径
if (!Directory.Exists(imgpath))
{
Directory.CreateDirectory(imgpath);
}
string picpath = System.Web.HttpContext.Current.Server.MapPath("/Upload/" + a3);//文件路径
string newname = imgpath + a1 + " " + a2 + ".pdf";//重命名
string nf = Path.Combine(newname);//生成新路径
File.Copy(picpath, nf);//复制
}
}
写法2、
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
///查询指定文件夹下所有文件
string path = Server.MapPath("Management/Upload/");
DirectoryInfo di = new DirectoryInfo(path);
//找到该目录下的文件
//FileInfo[] fis = di.GetFiles();
//foreach (FileInfo fi in fis)
//{
// Response.Write(fi.Name);//文件名称 不包含文件夹
// Response.Write(fi.Length);//文件大小
// Response.Write(fi.FullName);//文件名称路径
// Response.Write("<br>");
//}
//找到该目录下的文件夹
foreach (DirectoryInfo sub in di.GetDirectories())
{
Response.Write(sub.Name);
//添加指定文件到指定文件夹
// CreateFolder(g);//新建文件夹
CopyFile("Management/Upload/default.jpg", "Management/Upload/" + sub.Name + "/default.jpg");
}
}
public static void CreateFolder(string FolderPathName)
{
if (FolderPathName.Trim().Length > 0)
{
try
{
string CreatePath = System.Web.HttpContext.Current.Server.MapPath("Management/Upload/" + FolderPathName).ToString();
if (!Directory.Exists(CreatePath))
{
Directory.CreateDirectory(CreatePath);
}
}
catch
{
throw;
}
}
}
public void CopyFile(string SourceFile, string ObjectFile)
{
string sourceFile = Server.MapPath(SourceFile);
string objectFile = Server.MapPath(ObjectFile);
if (System.IO.File.Exists(sourceFile))
{
System.IO.File.Copy(sourceFile, objectFile, true);
}
}
}