The FileStream object represents a stream that points to a file on a disk or network path.
You can use the FileStream class to read, write, open, close, and so on files on a file system.
Nonsense don't say, start operation.
1. Drag the control, must drop, in addition to the text box to write the file, the other text box ReadOnly properties are set to True!
2. Start the Select File operation
Privatevoid Btnreadchoose_click (object sender, EventArgs e)
{
//Create Open File dialog box, you can drag the control directly ha ...
OpenFileDialog ofd=new OpenFileDialog ();
Displays the file path in the text box
if (OFD). ShowDialog () = = DialogResult.OK)
{
Txtreadpath.text = ofd. FileName;
}
}
Effect Chart ... The path is displayed.
3. Start the "read out" operation and display the text content in the text box.
First, write a way to show "warm tip" messages.
#region Show a warm message +void msgshow (string Msg)
///<summary>
///message with warm tips
///</summary>
// /<param name= "MSG" > Message </param>
void Msgshow (string Msg)
{
lbresult.text = "Warm tip:" +MSG;
}
#endregion
Read out operation
Privatevoid Btnreadfile_click (object sender, EventArgs e)
{
//create file stream, stream operation to perform exception handling, and use to release object
try
{
using (FileStream FS =new FileStream (Txtreadpath.text, FileMode.Open))
{
//define buffer, 3M size
Byte[] Arrfiledata =newbyte[1024*1024*3];
The read file exists in Arrfiledata
FS. Read (arrfiledata, 0, arrfiledata.length);
The transcoding format is displayed in the text box txtreadmsg
string changetostring = Encoding.Default.GetString (arrfiledata);
Txtreadmsg.text = changetostring;
Msgshow ("text read succeeded!!!");
}
catch (Exception ex)
{
MessageBox.Show ("exception:" + ex.) message);
}
Effect Chart:
4. Start the "write" operation, select the file is not cumbersome, almost.
Privatevoid Btnwritefile_click (object sender, EventArgs e)
{
//Get the data string to write to text
Strwritedata = Txtwritemsg.text;
Try
{
using (FileStream FS =new FileStream (Txtwritepath.text, FileMode.Create))
{
//convert to binary write text
byte[] Arrwritedata = Encoding.Default.GetBytes (strwritedata);
Fs. Write (data buffer, write from the first byte, how many)
fs. Write (arrwritedata, 0, arrwritedata.length);
Msgshow ("Write text succeeded!!!");
}
catch (Exception ex)
{
MessageBox.Show ("exception:" + ex.) message);
}
Effect Chart:
Just like that, a file stream FileStream text write, read small program is completed. The main is their own summary, a deeper understanding of the flow of the process, so share this article!