經常有新手在做頁面的時候不注意路徑的安排,通常圖方便都寫成絕對路徑。結果在編輯的時候(非dreamware下)發現不能直接點開,非要經過服務器才可以看到效果。
於是寫了一段代碼,直接將這些有規律的絕對鏈接轉為相對鏈接,代碼如下:
程序代碼
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace FilePathTool
{
class FilePath
{
//文件的根目錄
static readonly string RootLocal = @"F:\workfolder\project\";
List<FileItem> files = new List<FileItem>();
public FilePath()
{
DirectoryInfo root = new DirectoryInfo(RootLocal);
GetFolders(root, 0,"");
DealFile();
Console.WriteLine(files.Count);
Console.Read();
}
/// <summary>
/// 得到文件夾
/// </summary>
void GetFolders(DirectoryInfo root, int Level, string path)
{
foreach (DirectoryInfo item in root.GetDirectories())
{
GetFolders(item, Level + 1, path + item.Name + "/");
}
//得到文件
foreach (FileInfo item in root.GetFiles())
{
files.Add(new FileItem {
Level = Level,
Name = item.Name,
Extension = item.Extension,
Path = item.FullName,
AbsolutePath = path
});
}
}
/// <summary>
/// 處理已得到的文件
/// </summary>
void DealFile()
{
foreach (FileItem item in files)
{
if (item.Extension == ".htm")
{
Console.WriteLine(item.AbsolutePath);
DealRepalce(item);
}
}
}
/// <summary>
/// 替換方法
/// </summary>
void DealRepalce(FileItem item)
{
FileInfo file = new FileInfo(item.Path);
string txt = File.ReadAllText(item.Path, Encoding.Default);
txt = RepalceProcess(txt, item);
Console.WriteLine(txt);
//Console.Read();
File.WriteAllText(item.Path, txt, Encoding.Default);
}
/// <summary>
/// 遍歷替換
/// </summary>
string RepalceProcess(string txt, FileItem model)
{
foreach (FileItem item in files)
{
string relativePath = item.AbsolutePath + item.Name;
if (txt.Contains(relativePath))
{
txt = RepalceSingle(txt, relativePath, item, model);
}
}
return txt;
}
/// <summary>
/// 替換
/// </summary>
string RepalceSingle(string txt, string relativePath, FileItem item, FileItem model)
{
//當文件在同一目錄下只不需要顯示路徑
if (item.AbsolutePath == model.AbsolutePath)
{
return txt.Replace("/" + relativePath, item.Name);
}
else
{
return txt.Replace("/" + relativePath, GetDeep(model.Level) + relativePath);
}
}
static string tempDeep = @"../";
/// <summary>
/// 按文件深度得到父路徑
/// </summary>
/// <param name="Level"></param>
/// <returns></returns>
string GetDeep(int Level)
{
string deep = "";
for (int i = 0; i < Level; i++)
{
deep += tempDeep;
}
return deep;
}
}
/// <summary>
/// 文件信息實體
/// </summary>
public class FileItem
{
public int Level
{
get;
set;
}
public string Name
{
get;
set;
}
public string Extension
{
get;
set;
}
public string Path
{
get;
set;
}
public string AbsolutePath
{
get;
set;
}
}
}