最近一直都很忙,非常抱歉好久沒有寫過部落格了。最近遇到拷貝遠端檔案的一些工作,比如我們發布的web站點的時候,開發提供乙個zip壓縮包,我們需要上傳到遠端的伺服器a,然後在部署(檔案拷貝)到遠端環境b和c,abc都在乙個區域網裡面。檔案壓縮需要引用 system.io.compression和system.io.compression.filesystem
首先我們需要乙個工具類來轉換檔案路徑,本地位址與遠端位址的轉換 比如192.168.0.1上的d:\test 轉換 為\\192.168.0.1\d$\test,檔案路徑的拼接,
publicclass
pathutil
路徑必須是全路徑且是本地路徑");
}localpath = localpath.replace("
:", "$"
);
return $@"
\\\"
; }
public
static
string getlocapath(string
remotepath)
路徑必須包含磁碟資訊");
}string temp = remotepath.substring(index - 1
); temp = temp.replace("
$", ":"
);
return
temp;
}public
static
string combine(string path1, string
path2)
else
if (!path1.endswith("
\\") && !path2.startswith("\\"
))
//if ((path1.endswith("\\") && !path2.startswith("\\")) ||
//(!path1.endswith("\\") && path2.startswith("\\")))
return path1 +path2;
}}
備份遠端目錄的資料夾 (首先備份遠端a目錄到本地臨時檔案zip->拷貝到遠端b->刪除本地臨時檔案zip)
還原遠端檔案(部署發布包)(遠端檔案解壓到本地臨時目錄->拷貝到目標伺服器->刪除本地臨時目錄)
資料夾得拷貝就比較簡單,遞迴呼叫檔案複製就okay了,比如 \\192.168.0.1\d$\test 拷貝到 \\192.168.0.2\d$\test下 (建議先刪除存在檔案在拷貝)。
#region 檔案操作部分//////把乙個目錄下的檔案拷貝的目標目錄下
/// ///
源目錄 ///
目標目錄
///移除檔名部分路徑
public
void copyfiles(string sourcefolder, string targerfolder, string removeprefix = ""
)
if (!directory.exists(targerfolder))
directoryinfo directory = new
directoryinfo(sourcefolder);
//獲取目錄下的檔案
fileinfo files =directory.getfiles();
foreach (fileinfo item in
files)
string temppath = item.fullname.replace(removeprefix, string
.empty);
temppath = targerfolder +temppath;
fileinfo fileinfo = new
fileinfo(temppath);
if (!fileinfo.directory.exists)
file.delete(temppath);
item.copyto(temppath,
true
); }
//獲取目錄下的子目錄
directoryinfo directors =directory.getdirectories();
foreach (var item in
directors)
}//////
備份遠端資料夾為zip檔案
/// ///
備份目錄
///目標檔案
///public
bool backzip(string sourcefolder, string
targertfile)
file.copy(tempfilename, targertfile,
true
); ret = true
; }
catch
(exception ex)
出錯");
}finally
}return
ret;
}//////
把遠端檔案還原為遠端目錄
/// ///
遠端檔案
///遠端目錄
///public
bool restorezip(string sourcefile, string
targetfolder)
string copyfolder =tempfoldername;
//if (!directory.getfiles(copyfolder).any() && directory.getdirectories(copyfolder).length == 1)
//copyfiles(copyfolder, targetfolder, copyfolder);
ret = true
; }
catch
(exception ex)
到出錯");
}finally
}return
ret;
}#endregion
C 資料夾拷貝
using system using system.collections.generic using system.text using system.collections using system.io using system.windows.forms namespace gwmultme...
C 拷貝資料夾
拷貝資料夾中的所有內容至另外乙個該資料夾 原資料夾路徑名 目標資料夾路徑名 private static void copydirectory string srcdir,string desdir if directory.exists desdir 拷貝當前資料夾下所有檔案 try拷貝至 f,d...
linux scp遠端拷貝檔案及資料夾
1 拷貝本機 home administrator test整個目錄至遠端主機192.168.1.100的 root目錄下 複製 如下 scp r home administrator test root 192.168.1.100 root 2 拷貝單個檔案至遠端主機 複製 如下 scp home...