在安裝程式中,有時會遇到它的設計是:
移除的檔案 若所在的資料夾 有其他檔案或資料夾,就只把安裝的檔案刪除,仍留下其他(可能是使用者自己放進去)的檔案/資料夾。
以下是用程式實作的範例:

using System.IO;
// ...
    private void DeleteAFile( string fileNamePath )
    {
        if ( File.Exists( fileNamePath ) )
            File.Delete( fileNamePath );

        string dirName = Path.GetDirectoryName( fileNamePath );

        DirectoryInfo di = null ;
        if ( Directory.Exists( dirName ) )
            di = new DirectoryInfo( dirName );

        while ( di != null && di.Parent != null )
        {
            if ( di.GetFiles().Length == 0
                    && di.GetDirectories().Length == 0 )
            {
                di.Delete();
            }
            di = di.Parent;
        }
    } // DeleteAFile()

#原創

參考:How to delete all files and folders in a directory?

 

arrow
arrow

    Robert 發表在 痞客邦 留言(0) 人氣()