FileStream适合与读写原始字节(二进制)数据。如果希望处理字符数据,那么StreamReader和StreamWriter等累更适合。这写累在后台使用了FileStream 对象,并且在原始字节处理层上面插入了一个高效的字符添写层。当关闭StremReader、StreamWriter也就关闭了底层的FileStrewam;
FileStrewam写入文件:
- string LineText = "test";
- char[] charDataValue = LineText.ToCharArray();//转化为字符数组
- byte[] byDataValue = new byte[charDataValue.Length];
- //将字符数组转化为字节数组
- Encoder ec = Encoding.UTF8.GetEncoder();
- ec.GetBytes(charDataValue, 0, charDataValue.Length, byDataValue, 0, true);
- fs.Write(byDataValue, 0, byDataValue.Length);
fs.Seek(0, SeekOrigin.End);//追加数据
StreamReader写入中文
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None);//创建文件流
StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));//支持中文
sw.WriteLine("test");
创建csv文件
private void CreateTxtExcelFile()
{
string Filename = DateTime.Now.ToString("yyyy-MMdd-ss") + ".csv";//excel文件名
string abPath = AppDomain.CurrentDomain.BaseDirectory + "Excel//" + Filename;//Excel存放路径
FileStream s=null;
if (File.Exists(abPath))
{ File.Delete(abPath); }//删除重名的文件
try
{
s=File.Create(abPath);//根据文件名创建Excel文件
Excelpath = abPath;//记录Excel文件的路径
s.Close();
}
catch
{
MessageBox.Show("无法在本地创建Exce文件!");
}
}
向csv插入数据
FileStream fs = new FileStream(Excelpath, FileMode.Open, FileAccess.Write, FileShare.None);//创建文件流
StreamWriter sw = new StreamWriter(fs,Encoding.GetEncoding("gb2312"));//支持中文
string curNumber, curPass;
String LineText = "";//插入Excel的语句
if (!isAppend)//插入标题
{
LineText = "卡号,密码,面值";
sw.WriteLine(LineText);
isAppend = true;
}
else//追加数据
{
fs.Seek(0, SeekOrigin.End);
}
for (int i = 0; i < Total; i++)
{
Number++;//流水号
string temp = string.Format("{0:0000000000}", Number);//格式化数字
curNumber = Pre + temp;
string pass;
curPass = GetPass(16, Type,out pass);
LineText = "/""+curNumber+"/"/t,/""+pass+"/"/t,"+Value+"/n";
char[] charDataValue = LineText.ToCharArray();//转化为字符数组
byte[] byDataValue = new byte[charDataValue.Length];
//将字符数组转化为字节数组
Encoder ec = Encoding.UTF8.GetEncoder();
ec.GetBytes(charDataValue, 0, charDataValue.Length, byDataValue, 0, true);
fs.Write(byDataValue, 0, byDataValue.Length);
}
sw.Close();
fs.Close();