當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# File.Replace(String, String, String)用法及代碼示例

File.Replace(字符串,字符串,字符串)是一個內置的 File 類方法,用於將指定目標文件的內容替換為源文件的內容,然後刪除源文件並創建替換文件的備份。
用法:

public static void Replace (string sourceFileName, string destinationFileName, string destinationBackupFileName); 
 

參數:此函數接受三個參數,如下所示:

  • sourceFileName: This is the specified source file.
  • destinationFileName: This is the specified destination file whose contents get replaced with the contents of the source file.
  • destinationBackupFileName: This file contains the backup of replaced destination file’s content.

異常:

  • ArgumentException:destinationFileName 參數描述的路徑不是合法形式。或者 destinationBackupFileName 參數描述的路徑不是合法形式。
  • ArgumentNullException:destinationFileName 參數為空。
  • DriveNotFoundException:指定的驅動器無效。
  • FileNotFoundException:找不到當前 FileInfo 對象描述的文件。或者找不到destinationBackupFileName 參數描述的文件。
  • IOException:打開文件時發生 I/O 錯誤。或 sourceFileName 和 destinationFileName 參數指定相同的文件。
  • PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
  • PlatformNotSupportedException:操作係統是Windows 98 Second Edition 或更早版本,文件係統不是NTFS。
  • UnauthorizedAccessException:sourceFileName 或 destinationFileName 參數指定隻讀文件。 OR 當前平台不支持此操作。 OR 源或目標參數指定目錄而不是文件。或者調用者沒有所需的權限。

下麵是說明 File.Replace(String, String, String) 方法的程序。
程序1:在運行下麵的代碼之前,已經創建了三個文件,其中源文件是file1.txt,目標文件是file2.txt,備份文件是file3.txt。這些文件的內容如下所示-

file1.txt

file2.txt

file3.txt

C#


//C#程序來說明用法
//File.Replace(String, String, String) 方法

//使用 System 和 System.IO 命名空間
使用係統;
使用 System.IO;

類 GFG {
公共靜態無效 Main()
{
//指定3個文件
字符串源文件名 = "file1.txt";
字符串目標文件名 = "file2.txt";
字符串 destinationBackupFileName = "file3.txt";

//調用 Replace() 函數
File.Replace(源文件名,目標文件名,
目標備份文件名);

Console.WriteLine("更換過程已經完成。");
}
}

輸出:

Replacement process has been done.

運行上述代碼後,顯示如上輸出,源文件被刪除,剩下的兩個文件的內容如下所示——

file7.txt

file8.txt

程序2:在運行以下代碼之前,已經創建了兩個文件,其中源文件是 file1.txt,目標文件是 file2.txt 並且沒有備份文件,因為我們不想保留替換文件的備份。這些文件的內容如下所示-

file1.txt

file2.txt

C#


// C# program to illustrate the usage
// of File.Replace(String, String, String) method
  
// Using System and System.IO namespaces
using System;
using System.IO;
  
class GFG {
    public static void Main()
    {
        // Specifying 2 files
        string sourceFileName = "file1.txt";
        string destinationFileName = "file2.txt";
  
        // Calling the Replace() function with
        // null parameter inplace of backup file because
        // we do not want to keep backup of the
        // replaced file.
        File.Replace(sourceFileName, destinationFileName, null);
  
        Console.WriteLine("Replacement process has been done.");
    }
}

輸出:

Replacement process has been done.

運行上述代碼後,顯示如上輸出,源文件被刪除,目標文件內容如下所示——

file2.txt


相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.Replace(String, String, String) Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。