ASP tutorial. NET C # Read and write file application examples and detailed explanation
1. Use FileStream to read and write files
File header:
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;
Read the file Core code:
byte[] Bydata = new byte[100];
char[] Chardata = new char[1000];
Try
{
FileStream sfile = new FileStream ("File path", FileMode.Open);
Sfile.seek (Seekorigin.begin);
Sfile.read (bydata, 0, 100); The first parameter is an array of bytes that are passed in to accept the data in the FileStream object, and the 2nd parameter is the position in the byte array where the data is written, usually 0, to write data to the array from the beginning file of the array, and the last parameter to specify how many characters to read from the file
}
catch (IOException E)
{
Console.WriteLine ("An IO exception has been thrown!");
Console.WriteLine (E.tostring ());
Console.ReadLine ();
Return
}
Decoder d = Encoding.utf8.getdecoder ();
D.getchars (bydata, 0, Bydata.length, chardata, 0);
Console.WriteLine (Chardata);
Console.ReadLine ();
Write file Core code:
FileStream fs = new FileStream (file path, filemode.create);
Get byte array
byte [] Data =new utf8encoding (). GetBytes (string);
Start writing
Fs.write (data,0,data.length);
Empty buffer, close stream
Fs.flush ();
Fs.close ();
2. Use StreamReader and StreamWriter
File header:
using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;
StreamReader Read files:
StreamReader objreader = new StreamReader (file path);
String Sline= "";
ArrayList linelist = new ArrayList ();
while (sline!= null)
{
sline = objReader.ReadLine ();
if (sline!= null&&!sline.equals (""))
Linelist.add (sline);
}
Objreader.close ();
return linelist;
StreamWriter Write File:
FileStream fs = new FileStream (file path, filemode.create);
StreamWriter sw = new StreamWriter (FS);
Start writing
Sw.write (string);
Empty buffer
Sw.flush ();
Close the stream
Sw.close ();
Fs.close ();