一:讀檔案(利用FileStream對象)
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ReadFile
{
class Program
{
static void Main(string[] args)
{
byte[] byteData = new byte[200];
char[] charData = new char[200];
try
{
string fileName = "D:\\2.txt";
FileStream aFile = new FileStream(fileName, FileMode.Open);
aFile.Seek(113, SeekOrigin.Begin);
aFile.Read(byteData, 0, 200);
}
catch (IOException e)
{
Console.WriteLine("A IO Exception has been throw!");
Console.WriteLine("{0}",e.ToString());
Console.ReadKey();
return;
}
Decoder decoder = Encoding.UTF8.GetDecoder();
decoder.GetChars(byteData,0,byteData.Length,charData,0);
Console.WriteLine("{0}",charData);
Console.ReadKey();
}
}
}
二:寫檔案(利用FileStream對象)
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace WriteFile
{
class Program
{
static void Main(string[] args)
{
byte[] byteData;
char[] charData;
try
{
string fileName = "D:\\3.txt";
FileStream aFile = new FileStream(fileName, FileMode.Create);
charData = "HelloWorld".ToCharArray();
byteData = new byte[charData.Length];
//将字元數組轉換為位元組數組
Encoder e = Encoding.UTF8.GetEncoder();
e.GetBytes(charData, 0, charData.Length, byteData, 0, true);
aFile.Seek(0, SeekOrigin.Begin);
aFile.Write(byteData, 0, byteData.Length);
}
catch (IOException e)
{
Console.WriteLine("A IO Exception has been throw!");
Console.WriteLine("{0}", e.ToString());
Console.ReadKey();
return;
}
}
三:利用StreamWriter對象寫檔案
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
namespace StreamWrite
{
class Program
{
static void Main(string[] args)
{
try
{
FileStream aFile = new FileStream("D:\\Log.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
bool truth = true;
sw.WriteLine("Hello!Log!"); 利用WriteLine()寫一行字元串
sw.WriteLine("It is now {0} and things are longking good.", DateTime.Now.ToLongDateString());
sw.WriteLine("More than that,");
sw.Write("it's {0} that c# is fun.", truth);
sw.Close();
}
catch (IOException e)
{
Console.WriteLine("A IO Exception has been throw!");
Console.WriteLine("{0}", e.ToString());
Console.ReadKey();
return;
}
}
}
}
}
}
四:讀檔案(通過streamreader對象)
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace StreamRead
{
class Program
{
static void Main(string[] args)
{
try
{
String fileName = "D:\\Log.txt";
FileStream fs = new FileStream(fileName, FileMode.Open);
StreamReader sr = new StreamReader(fs);
int a = sr.Read();//Read()是讀出int型
Console.WriteLine("{0}", a);
string b =sr.ReadLine();//ReadLine()來讀出字元串型
while (b != null)
{
Console.WriteLine("{0}", b);
b = sr.ReadLine();
}
sr.Close();
}
catch (IOException e)
{
Console.WriteLine("A error !");
Console.WriteLine(e.ToString());
}
Console.ReadKey();
}
}
}