2007-08-15

用C#改檔名

今天有個需求,
需要有個功能將遠端的檔案用webclient下載下來存成暫存的檔名後,
確定沒有問題再將它更名為原本的檔名.

但是,寫到要更改檔名時,
發現.net的System.IO中似乎沒有rename的功能,
所以需要使用Copy或是Move的方法來達成.

而用Copy的話,會有個問題,就是當檔案大的時候會很慢,
而且還是要需求看是否要刪除原本的檔案.
所以比較合適的方式是用move.
更名的程式片段如下 :

public bool Rename(string  source,string dest)
{
    try
    {
        if  (!(File.Exists(source))) return false;
        string  dest  =  GenDestName(source); 
        if  (File.Exists(dest))
        {
            return false; 
        }
        File.Move(source,  dest); 
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

沒有留言:

當開發機是Windows on ARM...

 在MacOS上要使用windows去編譯一些程式常常會遇到一些plamform的問題... - cmake build failed 當使用 cmake -S . -B build 要建立 build system files 原本的專案是在x64上, 所以直接執行會直接使用A...