C#数据的读写操作
读取数据
使用 FileStream类读取数据不像使用 StreamReader 类读取数据那样容易。
原因:FileStream 类只能处理原始字节,从而可以读取任何数据文件,而不仅仅是文本文件。
通过读取字节数据,该类可以用于读取图像和声音的文件。灵活性的代价:不能使用
FileStream 类将数据将数据直接读入字符串,而 StreamReader 类却可以这样处理。
有几种转换类可以很容易的实现从字节数组和字符数组间的转换。例如 SystemText 名称空
间的 Decoder 类。
下面具体以一个实例介绍
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
byte[] bydate = new byte[20000];
char[] chardate = new char[20000];
try
{
FileStream afile = new FileStream("C:/tempuploads/Tell
Me Why -Declan Galbraith.mp3", FileMode.Open);
afile.Seek(113, SeekOrigin.Begin);
afile.Read(bydate, 0, 20000);
}
catch(IOException e)
{
Console.WriteLine("An IO exeption has been thrown !");
Console.WriteLine(e.ToString());
Console.ReadKey();
return;
}
Decoder d = Encoding.UTF8.GetDecoder();
d.GetChars(bydate,0,bydate.Length,chardate,0);
Console.WriteLine(chardate);
Console.ReadKey();
评论5