StreamReader
StreamReader sr = new StreamReader("qiufeng.txt", Encoding.GetEncoding("gb2312"));
Console.WriteLine(sr.ReadLine());
Console.Wri
teLine(sr.ReadLine());
使用ReadLine()读取,每次读一行,并且每次读取的时候,从上次读取的下一行开始,并且,当文档读完的时候,返回空
string str2 = string.Empty;
while ((str2 = sr.ReadLine()) != null)
{
Console.WriteLine(str2);
}
读取文档的每一行。他和string str3 = sr.ReadToEnd();
是等价的。
WriteAllLines
string[] str = {
"山中相送罢,",
"日暮掩柴扉。",
"春草明年绿,",
"王孙归不归。"
};
File.WriteAllLines("qiufeng.txt", str);
会写入qiufeng.txt,并且如果原来文档中有数据会清空再增加
File.WriteAllText(@"D:\2.txt",sb.ToString());
sb是一个StringBuilder,
File.AppendAllText("qiufeng.txt", str1)是追加数据
FileStream
复制视频
FileStream fs = new FileStream(@"d:\01复习1.avi", FileMode.Open, FileAccess.Read);
FileStream fs2 = new FileStream(@"d:\01复习2.avi", FileMode.Create, FileAccess.Write);
byte[] bs = new byte[1024*1024*10];
using (fs)
{
using (fs2)
{
int count;
do
{
count = fs.Read(bs, 0, bs.Length);
fs2.Write(bs, 0, count);
} while (count != 0);
}
}
先将数据用byte[]数组接受,注意我们这里是视频文件,如果数组设置过小,会造成频繁读取硬盘,我们这里设置为10M;
文件的加密解密:
我们可以在字节中插入密钥,如加1
using(FileStream fs1=new FileStream(@"d:\girl.mp3",FileMode.Open,FileAccess.Read))
{
using (FileStream fs2 = new FileStream(@"d:\newgirl.mp3", FileMode.Create, FileAccess.Write))
{
//MP3设置一M就可以了
byte[] bs = new byte[1024 * 1024];
int count = 0;
while ((count = fs1.Read(bs, 0, bs.Length)) > 0)
{
//有了一个字节数组
//如果将每个字节原封不动的写入新文件中,则表示copy
//如果要加密,需要一个密钥,咱就设为1,在每一个字节上加上一个数字1
for (int i = 0; i < bs.Length; i++)
{
bs[i]++;
}
fs2.Write(bs, 0, count);
}
}
}
解密则是减去一:
using (FileStream fs1 = new FileStream(@"d:\newgirl.mp3", FileMode.Open, FileAccess.Read))
{
using (FileStream fs2 = new FileStream(@"d:\DeCodegirl.mp3", FileMode.Create, FileAccess.Write))
{
//MP3设置一M就可以了
byte[] bs = new byte[1024 * 1024];
int count = 0;
while ((count = fs1.Read(bs, 0, bs.Length)) > 0)
{
//有了一个字节数组
//如果将每个字节原封不动的写入新文件中,则表示copy
//如果要加密,需要一个密钥,咱就设为1,在每一个字节上加上一个数字1
for (int i = 0; i < bs.Length; i++)
{
bs[i]--;
}
fs2.Write(bs, 0, count);
}
}
}