這是一份簡單的文件工具類,C#專用。剛接觸C#一個(gè)月,剛好業(yè)務(wù)需求,需要用到,于是自己就寫了一份出來,后續(xù)還會繼續(xù)更新......
‘’‘
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace ZoneTop.Util
{
/// <summary>
/// 常用公共類
/// </summary>
public class FileHelper
{
#region 文件管理
/// <summary>
/// 文件上傳,創(chuàng)建臨時(shí)物理路徑
/// </summary>
/// <param name="files">文件</param>
/// <param name="strPathPhysicalPart">物理路徑(不全)</param>
/// <param name="strPathNetPart">網(wǎng)絡(luò)路徑(不全)</param>
/// <returns>返回null創(chuàng)建失敗,返回string類型創(chuàng)建成功</returns>
public static string CreateTemp(HttpFileCollectionBase files, string strPathPhysicalPart, string strPathNetPart)
{
//創(chuàng)建虛擬路徑的文件目錄,以時(shí)間為單位創(chuàng)建文件名
DateTime dtFileDate = DateTime.Now;
string strFileDate = dtFileDate.ToString("yyyyMMdd");
strPathPhysicalPart = strPathPhysicalPart + "\" + strFileDate;
//文件數(shù)量大于或等于1個(gè)
if (files.Count > 0)
{
//獲取第一個(gè)文件
var file = files[0];
//判斷第一個(gè)文件是否有內(nèi)容
if (file.ContentLength > 0)
{
//判斷傳入的物理路徑是否存在,不存在創(chuàng)建
if (!Directory.Exists(strPathPhysicalPart))
{
Directory.CreateDirectory(strPathPhysicalPart);
}
//隨機(jī)創(chuàng)建文件名
string strFileName = System.Guid.NewGuid().ToString() + file.FileName.Substring(file.FileName.LastIndexOf("."));
//獲取文件全路徑
string strPathPhysical = strPathPhysicalPart + "\\" + strFileName;
string strPathNet = strPathNetPart + "/" + strFileDate + "/" + strFileName;
//寫入文件
file.SaveAs(strPathPhysical);
return strPathNet;
}
else
{
return null;
}
}
else
{
return null;
}
}
/// <summary>
/// 刪除臨時(shí)文件夾
/// </summary>
/// <param name="strTemp"></param>
/// <returns>返回布爾類型</returns>
public static bool DeleteTemp(string strTemp)
{
DirectoryInfo directoryInfo = new DirectoryInfo(strTemp);
if (directoryInfo.Exists)
{
directoryInfo.Delete();
return true;
}
else
{
return false;
}
}
/// <summary>
/// 刪除臨時(shí)文件夾下(有包含文件)
/// </summary>
/// <param name="strTemp"></param>
/// <returns>返回布爾類型</returns>
public static bool DeleteTemp(string strTemp, bool isFile)
{
DirectoryInfo directoryInfo = new DirectoryInfo(strTemp);
if (directoryInfo.Exists)
{
directoryInfo.Delete(isFile);
return true;
}
else
{
return false;
}
}
public void SaveFile()
{
}
#endregion
}
}
’‘’