C#實現的對文件的重命名

    以下C#實現對文件的重命名的方法須要傳入三個string類型的參數,分別是源文件的文件目錄、目的文件目錄和重命名的文件名稱,實現代碼以下:spa

public ExecutionResult FileRename(string sourceFile, string destinationPath, string destinationFileName)
        {
            ExecutionResult result;
            FileInfo tempFileInfo;
            FileInfo tempBakFileInfo;
            DirectoryInfo tempDirectoryInfo;

            result = new ExecutionResult();
            tempFileInfo = new FileInfo(sourceFile);
            tempDirectoryInfo = new DirectoryInfo(destinationPath);
            tempBakFileInfo = new FileInfo(destinationPath + "\\" + destinationFileName);
            try
            {
                if (!tempDirectoryInfo.Exists)
                    tempDirectoryInfo.Create();
                if (tempBakFileInfo.Exists)
                    tempBakFileInfo.Delete();
                //move file to bak
                tempFileInfo.MoveTo(destinationPath + "\\" + destinationFileName);

                result.Status = true;
                result.Message = "Rename file OK";
                result.Anything = "OK";
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Anything = "Mail";
                result.Message = ex.Message;
                if (mesLog.IsErrorEnabled)
                {
                    mesLog.Error(MethodBase.GetCurrentMethod().Name, "Rename file error. Msg :" + ex.Message);
                    mesLog.Error(ex.StackTrace);
                }
            }

            return result;
        }
相關文章
相關標籤/搜索