在 C# 中讀取檔案的不同方式
在這裡,我們讀取了兩個不同的檔案−
讀取文字檔案 −
示例
using System;
using System.IO;
namespace FileApplication {
class Program {
static void Main(string[] args) {
try {
using (StreamReader sr = new StreamReader("d:/new.txt")) {
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
} catch (Exception e) {
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}輸出
The file could not be read: Could not find a part of the path "/home/cg/root/4281363/d:/new.txt".
讀取二進位制檔案 −
示例
using System.IO;
namespace BinaryFileApplication {
class Program {
static void Main(string[] args) {
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3.14157;
bool b = true;
string s = "I am happy";
//create the file
try {
bw = new BinaryWriter(new FileStream("mydata", FileMode.Create));
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot create file.");
return;
}
//writing into the file
try {
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot write to file.");
return;
}
bw.Close();
//reading from the file
try {
br = new BinaryReader(new FileStream("mydata", FileMode.Open));
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot open file.");
return;
}
try {
i = br.ReadInt32();
Console.WriteLine("Integer data: {0}", i);
d = br.ReadDouble();
Console.WriteLine("Double data: {0}", d);
b = br.ReadBoolean();
Console.WriteLine("Boolean data: {0}", b);
s = br.ReadString();
Console.WriteLine("String data: {0}", s);
} catch (IOException e) {
Console.WriteLine(e.Message + "
Cannot read from file.");
return;
}
br.Close();
Console.ReadKey();
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP