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


C# File.WriteAllBytes()用法及代碼示例

File.SetLastWriteTimeUtc(String)是內置的File類方法,用於創建新文件,然後將指定的字節數組寫入文件,然後關閉文件。如果目標文件已經存在,則將其覆蓋。

用法:

public static void WriteAllBytes (string path, byte[] bytes);

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



  • path: This is the specified file where the byte array is going to be written.
  • bytes: This is the specified bytes that are going to be written into the file.

異常:

  • ArgumentException:路徑為長度為零的字符串,僅包含空格,或者由InvalidPathChars定義的一個或多個無效字符。
  • ArgumentNullException:路徑為空或字節數組為空。
  • PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
  • DirectoryNotFoundException:指定的路徑無效。
  • IOException:打開文件時發生I /O錯誤。
  • UnauthorizedAccessException:該路徑指定了一個隻讀文件。或路徑指定了隱藏的文件。或者當前平台不支持此操作。或路徑指定目錄。或調用者沒有所需的權限。
  • NotSupportedException:路徑格式無效。
  • SecurityException:調用者沒有所需的權限。

下麵是說明File.WriteAllBytes(String,Byte [])方法的程序。

程序1:最初,沒有創建文件。在代碼下麵,它自己創建一個文件file.txt並寫入一些指定的字節數組,然後最後關閉該文件。

// C# program to illustrate the usage 
// of File.WriteAllBytes() method 
  
// Using System, System.IO 
// and System.Text namespaces 
using System; 
using System.IO; 
using System.Text; 
  
class GFG { 
    static void Main(string[] args) 
    { 
        // Specifing a file name 
        var path = @"file.txt"; 
  
        // Specifing a byte array 
        string text = "GFG is a CS portal."; 
        byte[] data = Encoding.ASCII.GetBytes(text); 
  
        // Calling the WriteAllBytes() function 
        // to write specified byte array to the file 
        File.WriteAllBytes(path, data); 
        Console.WriteLine("The data has been written to the file."); 
    } 
}

輸出:

The data has been written to the file.

上麵的代碼給出了如上所示的輸出,並創建了一個文件,其內容如下所示:

file.txt

程序2:最初,創建了一個文件,其內容如下所示:

file.txt

下麵的代碼用指定的字節數組數據覆蓋上麵的文件內容。

// C# program to illustrate the usage 
// of File.WriteAllBytes() method 
  
// Using System, System.IO 
// and System.Text namespaces 
using System; 
using System.IO; 
using System.Text; 
  
class GFG { 
    static void Main(string[] args) 
    { 
        // Specifing a file name 
        var path = @"file.txt"; 
  
        // Specifing a byte array data 
        string text = "GeeksforGeeks"; 
        byte[] data = Encoding.ASCII.GetBytes(text); 
  
        // Calling the WriteAllBytes() function 
        // to overwrite the file contents with the 
        // specified byte array data 
        File.WriteAllBytes(path, data); 
        Console.WriteLine("The data has been overwritten to the file."); 
    } 
}

輸出:

The data has been overwritten to the file.

運行以上代碼後,將顯示以上輸出,並且文件內容將被覆蓋,如下所示:

file.txt




相關用法


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