System.IO Namespaces for a. NET Framework class Library
The System.IO namespace contains types that allow you to read and write files and data streams, and types that provide basic file and directory support.
two C # file read and write FileStream
1. (FileStream FS1 = File.Open ("C://test.txt", FileMode.Open));
FileMode.Open Open File C://test.txt directly with the FileStream class.
2. (FileStream FS2 = File.Open ("C://test.txt", Filemode.append, FileAccess.Write));
Filemode.append, open the file "C://test.txt" in an additional way, and write some content to "C://test.txt".
3. (FileStream fs3 =file.open ("C://test.txt", Filemode.truncate, FileAccess.ReadWrite, FileShare.Read)).
Filemode.truncate means to open and empty the file and then manipulate the file.
4. FileStream MyFileStream1 = new FileStream (@ "C:/testing.txt", FileMode.Create);
This means creating a file that can be read and written, and allowing others to read the contents of the file.
Three stream is a very large class, when reading and writing files, you can use different streams for professional data reading and writing.
The following code implements the conversion between stream and byte using an input-output stream
Public byte[] Streamtobytes (Stream stream)
{
byte[] bytes = new Byte[stream. Length];
Stream. Read (bytes, 0, bytes. Length);
Sets the position of the current stream as the start of the stream
Stream. Seek (0, Seekorigin.begin);
return bytes;
}
Turn byte[] into a Stream
Public Stream bytestostream (byte[] bytes)
{
Stream stream = new MemoryStream (bytes);
return stream;
}
Write Stream to File
public void Streamtofile (Stream stream,string fileName)
{
Convert Stream to byte[]
byte[] bytes = new Byte[stream. Length];
Stream. Read (bytes, 0, bytes. Length);
Sets the position of the current stream as the start of the stream
Stream. Seek (0, Seekorigin.begin);
Write byte[] to file
FileStream fs = new FileStream (FileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter (FS);
Bw. Write (bytes);
Bw. Close ();
Fs. Close ();
}
Read Stream from File
Public Stream Filetostream (string fileName)
{
Open File
FileStream FileStream = new FileStream (FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
Read the file byte[]
byte[] bytes = new Byte[filestream.length];
FileStream.Read (bytes, 0, bytes. Length);
Filestream.close ();
Convert byte[] to Stream
Stream stream = new MemoryStream (bytes);
return stream;
}
byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes (xmlcontent);
String xmlcontent = System.Text.UTFEncoding.UTF8.GetString (bytes);
From string to flow stream
byte[] buffer = System.Text.Encoding.Unicode.GetBytes ("faint");
MemoryStream stream = new MemoryStream (buffer);
MemoryStream ms = new MemoryStream (System.Text.Encoding.Default.GetBytes (AOBJSTR));
C # about input and output streams (5)