要求:
利用WPF应用程序和filestream类实现文件的读写。
- 点击“创建文件”按钮,在D盘根目录创建一个名称为File的记事本文件;
- 点击“写文件”按钮,在File文件中输入“Hello,你好”信息;
- 点击“读文件”按钮,将下列文字信息复制到File文件中并原样输出到textBlock控件中。
文字样本:
一份微语报,众览天下事!
1、北京2019升学政策发布 公民同招 民办校也将计算机派位;
2、农业农村部:今起黄河开始全流域禁渔 为期三个月;
3、日本政府公布新年号为“令和” 初春令月,气淑风和;
4、三星Note7爆炸案终审判决:三星中国不用道歉,只赔被烧坏的电脑;5、美国迪士尼5月起禁烟,上海暂未同步;
6、四川凉山木里县森林火灾:扑火人员突遇山火爆燃,30人失联;
7、第六批在韩志愿军烈士遗骸4月3日回归祖国;
8、我国成功发射“天链二号01星”:成为在轨卫星、空间站和地面中心站的桥梁;
9、国家禁毒委:不断加强严格管理麻醉药品使用等问题;
10、卫健委:144个地级市已实现区域内医疗就诊“一卡通”;
11、斯洛伐克首位女总统:律师,无从政经验;
12、胜利夜店门再牵出新黑幕 韩国殿堂级合唱团体沦陷;
【微语】人在身处逆境时,适应环境的能力实在惊人。人可以忍受不幸,也可以战胜不幸,因为人有着惊人的潜力,只要立志发挥它,就一定能渡过难关。——卡耐基【微语】很多时候限制我们的,不是周遭的环境,也不是他人的言行,而是我们自己。
效果:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace ch05
{
/// <summary>
/// MainWindow.xaml的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
string path = @"D:\file1.txt";
private void button1_Click(object sender, RoutedEventArgs e)
{
FileStream fs = new FileStream(path,FileMode.OpenOrCreate,FileAccess.ReadWrite);
textBlock1.Text += "\n创建完毕";
fs.Close();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
string message = "Hello,你好";
byte[] bytes = new byte[10240];
bytes = Encoding.UTF8.GetBytes(message);
//bytes = Encoding.UTF8.GetBytes(message);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
fs.Position = fs.Length;
fs.Write(bytes, 0, bytes.Length);
fs.Close();
textBlock1.Text += "\n写入完毕";
}
private void button3_Click(object sender, RoutedEventArgs e)
{
byte[] bytes = new byte[10240];//开大一点避免乱码
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
int num=fs.Read(bytes, 0, bytes.Length);
string message="";
while (num > 0) //循环读出
{
message = Encoding.UTF8.GetString(bytes, 0, num);
num = fs.Read(bytes, 0, bytes.Length);
textBlock1.Text += message;
}
textBlock1.Text += "\n读出完毕";
}
}
}