程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#訪問文件路徑通用類

C#訪問文件路徑通用類

編輯:C#入門知識

C#訪問文件路徑通用類


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace Utility

{

///

/// @Author:梁繼龍

/// @Date:2012/8/1

/// @Email:[email protected]

/// @Description:文件處理類

///

public class AccessDirFileHelper

{

public static AccessDirFileHelper instance = null;

private static readonly object lockObj = new object();

protected static System.Reflection.Assembly assembly = null; //反射

///

/// 單例模式

///

///

public static AccessDirFileHelper GetInstance()

{

//lock (AccessFileHelper.instance){ }

if (instance == null)

{

lock (lockObj)

{

instance = new AccessDirFileHelper();

}

}

return instance;

}

///

/// 獲取當前進程的完整路徑,包含文件名(進程名)

/// result: X:\xxx\xxx\xxx.exe (.exe文件所在的目錄+.exe文件名

///

///

public string GetLocalProcessFileName()

{

try

{

return this.GetType().Assembly.Location;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 獲取新的 Process 組件並將其與當前活動的進程關聯的主模塊的完整路徑,包含文件名(進程名).

//result: X:\xxx\xxx\xxx.exe (.exe文件所在的目錄+.exe文件名)

///

///

public string GetCurrentProcessFileNamePath()

{

try

{

return System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 獲取和設置當前目錄(即該進程從中啟動的目錄)的完全限定路徑.

/// result: X:\xxx\xxx (.exe文件所在的目錄)

///

///

public String GetCurrentEnvironmentDirectoryPath()

{

try

{

return System.Environment.CurrentDirectory;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 獲取當前 Thread 的當前應用程序域的基目錄,它由程序集沖突解決程序用來探測程序集。

///string str = System.AppDomain.CurrentDomain.BaseDirectory;

///result: X:\xxx\xxx\ (.exe文件所在的目錄+"\")

///Example:用來判斷winfrom會少一個Debug E:\\ASP.NET\\MyApp\\WebApp\\bin\\Debug\\bin\\Utility.dll" web

///Example:用來判斷winfrom會多一個Debug E:\\ASP.NET\\MyApp\\WinApp\\bin\\Debug\\Utility.dll" winform

///此方法一般判斷一個解決方案啟動是web還是winform讀取文件(dll,config,txt等..)看情況定

///

public string GetCurrentDomainBaseDirectory()

{

try

{ //效果一樣

//System.Threading.Thread.GetDomain().BaseDirectory

return System.AppDomain.CurrentDomain.BaseDirectory;

}

catch (Exception e)

{

throw e;

}

}

///

/// 獲取和設置包含該應用程序的目錄的名稱。

///string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

///result: X:\xxx\xxx\ (.exe文件所在的目錄+"\")

///

///

public string GetCurrentDomainSetupInformationName()

{

try

{

return System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 獲取啟動了應用程序的可執行文件的路徑,不包括可執行文件的名稱

/// string str = System.Windows.Forms.Application.StartupPath;

/// result: X:\xxx\xxx (.exe文件所在的目錄)

///

///

public string GetWindowsApplicationStartupPath()

{

try

{

return System.Windows.Forms.Application.StartupPath;

}

catch (Exception e)

{

throw e;

}

}

///

///獲取啟動了應用程序的可執行文件的路徑,包括可執行文件的名稱。

///string str = System.Windows.Forms.Application.ExecutablePath;

///result: X:\xxx\xxx\xxx.exe (.exe文件所在的目錄+.exe文件名)

///

///

public string GetWindowsExecutablePath()

{

try

{

return System.Windows.Forms.Application.ExecutablePath;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 獲取應用程序的當前工作目錄(不可靠)

/// /string str = System.IO.Directory.GetCurrentDirectory();

/// result: X:\xxx\xxx (.exe文件所在的目錄)

///

///

public string GetCurrentDirectory()

{

try

{

return System.IO.Directory.GetCurrentDirectory();

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 這個方法的意思是:在同一個解決方案裡面有兩個工程,啟動的時候

/// 去判斷哪個工程是Winform或者是Web的配置

///Example:E:\\ASP.NET\\MyApp\\WinApp\\bin\\Debug\\MyApp.vshost.exe.Config" //winform

///Example:"E:\\ASP.NET\\MyApp\\WebApp\\web.config" //web

///從後面的配置截取Example:String index=Path3.Substring(config.Length - 8);截取

///後面字符串判去判斷,最好把都轉換成小寫或者大寫

///index.ToUpper()="E.CONFIG" / index.ToLower()=="e.config"

///

///

public System.Reflection.Assembly GetCurrentDomainConfigurationFile(string executeWinformConfig, string executeWebConfig)

{

try

{

string config = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

string index = config.Substring(config.Length - 8);

if (index.ToLower() == "e.config") //把截取到的字符串轉為為小寫

{

assembly = System.Reflection.Assembly.LoadFile(executeWinformConfig); //加載dll文件

}

if (index.ToLower() == "b.config")

{

assembly = System.Reflection.Assembly.LoadFile(executeWebConfig); //加載dll文件

}

return assembly;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 無參數的GetCurrentDomainConfigurationFile方法

/// GetCurrentDomainConfigurationFile

///

///

public string GetCurrentDomainConfigurationFile()

{

try

{

return AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// Application.StartupPath與AppDomain.CurrentDomain.BaseDirectory都是判斷

/// 當前啟動的工程,並體現能找到

/// Example:E:\\ASP.NET\\MyApp\\MyApp\\bin\\Debug路徑下面,唯有不同的就是

/// AppDomain.CurrentDomain.BaseDirectory多了個 \\

/// Application.StartupPath而且是System.Windows.Forms

///

///

public string GetStartupPath()

{

try

{

return System.Windows.Forms.Application.StartupPath;

}

catch (Exception)

{

throw;

}

}

///

/// 獲取文件的大小,一般指文件有多少個字節

///

///

///

public string GetFileSize(string fileName)

{

try

{

if (File.Exists(fileName))

{

return Convert.ToString(new FileInfo(fileName).Length);

}

else

return fileName;

}

catch (Exception)

{

throw;

}

}

///

///在卸載程序獲取系統安裝的目錄:

///System.Reflection.Assembly curPath = System.Reflection.Assembly.GetExecutingAssembly();

/// string path=curPath.Location;//得到安裝程序類SetupLibrary文件的路徑,獲取這個文件路徑

///所在的目錄即得到安裝程序的目錄;

///

///

public String GetExecutingAssemblyDirectory()

{

try

{

System.Reflection.Assembly curPath = System.Reflection.Assembly.GetExecutingAssembly();

string path = curPath.Location;

return path;

}

catch (Exception ex)

{

throw ex;

}

}

#region

///

/// 創建目錄

///

/// 此地路徑相對站點而言

public static void CreateDir(string dir)

{

if (dir.Length == 0) return;

if (!System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(dir)))

System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(dir));

}

///

/// 創建目錄路徑

///

/// 物理路徑

public static void CreateFolder(string folderPath)

{

if (!System.IO.Directory.Exists(folderPath))

System.IO.Directory.CreateDirectory(folderPath);

}

///

/// 刪除目錄

///

/// 此地路徑相對站點而言

public static void DeleteDir(string dir)

{

if (dir.Length == 0) return;

if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(dir)))

System.IO.Directory.Delete(System.Web.HttpContext.Current.Server.MapPath(dir), true);

}

///

/// 判斷文件是否存在

///

/// 格式:a/b.htm,相對根目錄

///

public static bool FileExists(string file)

{

if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(file)))

return true;

else

return false;

}

///

/// 讀取文件內容

///

/// 格式:a/b.htm,相對根目錄

///

public static string ReadFile(string file)

{

if (!FileExists(file))

return "";

try

{

System.IO.StreamReader sr = new System.IO.StreamReader(System.Web.HttpContext.Current.Server.MapPath(file), System.Text.Encoding.UTF8);

string str = sr.ReadToEnd();

sr.Close();

return str;

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 保存為不帶Bom的文件

///

///

/// 格式:a/b.htm,相對根目錄

public static void SaveFile(string TxtStr, string tempDir)

{

SaveFile(TxtStr, tempDir, true);

}

///

/// 保存文件內容,自動創建目錄

///

///

/// 格式:a/b.htm,相對根目錄

///

public static void SaveFile(string TxtStr, string tempDir, bool noBom)

{

try

{

CreateDir(GetFolderPath(true, tempDir));

System.IO.StreamWriter sw;

if (noBom)

sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, new System.Text.UTF8Encoding(false));

else

sw = new System.IO.StreamWriter(System.Web.HttpContext.Current.Server.MapPath(tempDir), false, System.Text.Encoding.UTF8);

sw.Write(TxtStr);

sw.Close();

}

catch (Exception ex)

{

throw ex;

}

}

///

/// 復制文件

/// 這個方法在6.0版本後改寫,雖看似比前面的版本冗長,但避免了file2文件一直被占用的問題

///

///

///

/// 如果已經存在是否覆蓋?

public static void CopyFile(string file1, string file2, bool overwrite)

{

if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(file1)))

{

if (overwrite)

System.IO.File.Copy(System.Web.HttpContext.Current.Server.MapPath(file1), System.Web.HttpContext.Current.Server.MapPath(file2), true);

else

{

if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(file2)))

System.IO.File.Copy(System.Web.HttpContext.Current.Server.MapPath(file1), System.Web.HttpContext.Current.Server.MapPath(file2));

}

}

}

///

/// 刪除文件

///

/// 此地路徑相對程序路徑而言

public static void DeleteFile(string file)

{

if (file.Length == 0) return;

if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(file)))

System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(file));

}

///

/// 獲得文件的目錄路徑

///

/// 文件路徑

/// 以\結尾

public static string GetFolderPath(string filePath)

{

return GetFolderPath(false, filePath);

}

///

/// 獲得文件的目錄路徑

///

/// 是否是網址

/// 文件路徑

/// 以\或/結尾

public static string GetFolderPath(bool isUrl, string filePath)

{

if (isUrl)

return filePath.Substring(0, filePath.LastIndexOf("/") + 1);

else

return filePath.Substring(0, filePath.LastIndexOf("\\") + 1);

}

///

/// 獲得文件的名稱

///

///

///

public static string GetFileName(string filePath)

{

return GetFileName(false, filePath);

}

///

/// 獲得文件的名稱

///

/// 是否是網址

///

///

public static string GetFileName(bool isUrl, string filePath)

{

if (isUrl)

return filePath.Substring(filePath.LastIndexOf("/") + 1, filePath.Length - filePath.LastIndexOf("/") - 1);

else

return filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.Length - filePath.LastIndexOf("\\") - 1);

}

///

/// 獲得文件的後綴

/// 不帶點,小寫

///

///

///

public static string GetFileExt(string filePath)

{

return filePath.Substring(filePath.LastIndexOf(".") + 1, filePath.Length - filePath.LastIndexOf(".") - 1).ToLower();

}

///

/// 目錄拷貝

///

///

///

public static void CopyDir(string OldDir, string NewDir)

{

DirectoryInfo OldDirectory = new DirectoryInfo(OldDir);

DirectoryInfo NewDirectory = new DirectoryInfo(NewDir);

CopyDir(OldDirectory, NewDirectory);

}

private static void CopyDir(DirectoryInfo OldDirectory, DirectoryInfo NewDirectory)

{

string NewDirectoryFullName = NewDirectory.FullName + "\\" + OldDirectory.Name;

if (!Directory.Exists(NewDirectoryFullName))

Directory.CreateDirectory(NewDirectoryFullName);

FileInfo[] OldFileAry = OldDirectory.GetFiles();

foreach (FileInfo aFile in OldFileAry)

File.Copy(aFile.FullName, NewDirectoryFullName + "\\" + aFile.Name, true);

DirectoryInfo[] OldDirectoryAry = OldDirectory.GetDirectories();

foreach (DirectoryInfo aOldDirectory in OldDirectoryAry)

{

DirectoryInfo aNewDirectory = new DirectoryInfo(NewDirectoryFullName);

CopyDir(aOldDirectory, aNewDirectory);

}

}

///

/// 目錄刪除

///

///

public static void DelDir(string OldDir)

{

DirectoryInfo OldDirectory = new DirectoryInfo(OldDir);

OldDirectory.Delete(true);

}

///

/// 目錄剪切

///

///

///

public static void CopyAndDelDir(string OldDirectory, string NewDirectory)

{

CopyDir(OldDirectory, NewDirectory);

DelDir(OldDirectory);

}

///

/// 文件下載

///

///

///

/// 源文件路徑

///

///

public static bool DownloadFile(System.Web.HttpRequest _Request, System.Web.HttpResponse _Response, string _fullPath, long _speed)

{

string _fileName = GetFileName(false, _fullPath);

try

{

FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

BinaryReader br = new BinaryReader(myFile);

try

{

_Response.AddHeader("Accept-Ranges", "bytes");

_Response.Buffer = false;

long fileLength = myFile.Length;

long startBytes = 0;

double pack = 10240; //10K bytes

//int sleep = 200; //每秒5次 即5*10K bytes每秒

int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;

if (_Request.Headers["Range"] != null)

{

_Response.StatusCode = 206;

string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });

startBytes = Convert.ToInt64(range[1]);

}

_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());

_Response.AddHeader("Connection", "Keep-Alive");

_Response.ContentType = "application/octet-stream";

_Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

for (int i = 0; i < maxCount; i++)

{

if (_Response.IsClientConnected)

{

_Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));

System.Threading.Thread.Sleep(sleep);

}

else

{

i = maxCount;

}

}

}

catch

{

return false;

}

finally

{

br.Close();

myFile.Close();

}

}

catch

{

return false;

}

return true;

}

#endregion

}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved