File.ReadAllBytes(String)是一個內置的File類方法,該方法用於打開指定的或創建的二進製文件,然後將文件的內容讀取到字節數組中,然後關閉文件。
用法:
public static byte[] ReadAllBytes (string path);
參數:該函數接受如下所示的參數:
- path: This is the specified file to open for reading.
異常:
- ArgumentException:路徑為長度為零的字符串,僅包含空格,或者由InvalidPathChars定義的一個或多個無效字符。
- ArgumentNullException:路徑為空。
- PathTooLongException:指定的路徑,文件名或兩者都超過了system-defined的最大長度。
- DirectoryNotFoundException:指定的路徑無效。
- IOException:打開文件時發生I /O錯誤。
- UnauthorizedAccessException:當前平台不支持此操作。或路徑指定目錄。或調用者沒有所需的權限。
- FileNotFoundException:找不到在路徑中指定的文件。
- NotSupportedException:路徑格式無效。
- SecurityException:調用者沒有所需的權限。
返回值:返回一個包含文件內容的字節數組。
下麵是說明File.ReadAllBytes(String)方法的程序。
程序1:最初,將創建一個文件file.txt,其內容如下所示-
// C# program to illustrate the usage
// of File.ReadAllBytes(String) method
// Using System and System.IO namespaces
using System;
using System.IO;
class GFG {
public static void Main()
{
// Specifing a file
string path = @"file.txt";
// Calling the ReadAllBytes() function
byte[] readText = File.ReadAllBytes(path);
foreach(byte s in readText)
{
// Printing the binary array value of
// the file contents
Console.WriteLine(s);
}
}
}
輸出:
53
程序2:最初,沒有創建文件。下麵的代碼本身創建帶有一些指定內容的文件file.txt。
// C# program to illustrate the usage
// of File.ReadAllBytes(String) method
// Using System and System.IO namespaces
using System;
using System.IO;
class GFG {
public static void Main()
{
// Specifing a file
string path = @"file.txt";
// Adding below contents to the file
string[] createText = { "GFG" };
File.WriteAllLines(path, createText);
// Calling the ReadAllBytes() function
byte[] readText = File.ReadAllBytes(path);
foreach(byte s in readText)
{
// Printing the binary array value of
// the file contents
Console.WriteLine(s);
}
}
}
輸出:
71 70 71 10
相關用法
- C# MathF.Cos()用法及代碼示例
- C# MathF.Sin()用法及代碼示例
- C# MathF.Min()用法及代碼示例
- C# MathF.Max()用法及代碼示例
- C# MathF.Log()用法及代碼示例
- C# MathF.Abs()用法及代碼示例
- C# MathF.Exp()用法及代碼示例
- C# MathF.Pow()用法及代碼示例
- C# MathF.Tan()用法及代碼示例
- C# Int16.Equals用法及代碼示例
- C# SByte.Equals用法及代碼示例
- C# UInt16.GetHashCode用法及代碼示例
- C# SByte.GetTypeCode用法及代碼示例
- C# SByte.GetHashCode用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.ReadAllBytes() Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。