c#读取文件,重新建立文件,把读取的数据放入到文件中去
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace OperateFile
{
//获取图片的数据,然后将数据存储到另一张图片中去。
class Program
{
static void Main(string[] args)
{
try
{
FileInfo fileInfo = new FileInfo("zhl.jpg");
int fileSize = (int)(fileInfo.Length);
FileStream afile = new FileStream("zhl.jpg", FileMode.Open);
FileStream writefile = new FileStream("new.jpg", FileMode.CreateNew);
//首先获取文件大小
byte[] dataByte = new byte[1024];
int i = (int)fileSize / 1024;
int yu = (int)fileSize % 1024;
//<1024byte的时候
//==1024 byte的时候
//>1024 byte的 时候,余数为0和不为0
if (fileSize < 1024)
{
//在此处写入到2.jpg文件中
afile.Seek(0, SeekOrigin.Begin);
afile.Read(dataByte, 0, fileSize);
writefile.Write(dataByte, 0, fileSize);
writefile.Close();
afile.Close();
}
else if (fileSize == 1024)
{
afile.Seek(0, SeekOrigin.Begin);
afile.Read(dataByte, 0, fileSize);
writefile.Write(dataByte, 0, fileSize);
writefile.Close();
afile.Close();
}
else
{
if (yu != 0)
{
for (int j = 0; j <i; j++)
{
afile.Seek(j * 1024, SeekOrigin.Begin);
afile.Read(dataByte, 0, 1024);
writefile.Write(dataByte, 0, 1024);
}
int seekNum = i * 1024;
long operNum = (long)seekNum;
afile.Seek(operNum, SeekOrigin.Begin);
afile.Read(dataByte, 0, yu);
writefile.Write(dataByte, 0, yu);
writefile.Close();
afile.Close();
}
else
{
for (int j = 0; j < i; j++)
{
afile.Seek(j * 1024, SeekOrigin.Begin);
afile.Read(dataByte, 0, 1024);
writefile.Write(dataByte, 0, 1024);
}
writefile.Close();
afile.Close();
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}