C# WPF 文件操作

来源:互联网 发布:高一历史优化设计答案 编辑:程序博客网 时间:2024/04/28 21:53

文件读写
- 读文件

FileStream fs = new FileStream(@"C:\Users\weixin\Desktop\latex\file.txt", FileMode.Open, FileAccess.Read);StreamReader m_streamReader = new StreamReader(fs);//使用StreamReader类来读取文件m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);//从数据流中读取每一行,直到文件的最后一行,并在textBox中显示出内容,其中textBox为文本框,如果不用可以改为别的this.textBox.Text = "";string strLine = m_streamReader.ReadLine();while (strLine != null){    this.textBox.Text += strLine + "\n";    strLine = m_streamReader.ReadLine();}//关闭此StreamReader对象m_streamReader.Close();

- 写文件

FileStream fs = new FileStream(@"C:\Users\weixin\Desktop\latex\file.txt", FileMode.OpenOrCreate, FileAccess.Write);StreamWriter m_streamWriter = new StreamWriter(fs);m_streamWriter.Flush();//设置当前流的位置m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);//写入内容m_streamWriter.Write("锄禾日当午");m_streamWriter.Write("\r\n");//换行m_streamWriter.Write("汗滴禾下土");m_streamWriter.Write("\r\n");//换行m_streamWriter.Write("谁知盘中餐");m_streamWriter.Write("\r\n");//换行m_streamWriter.Write("粒粒皆辛苦");//关闭此文件m_streamWriter.Flush();m_streamWriter.Close();

判定相应位置下的文件是否存在

string path = AppDomain.CurrentDomain.BaseDirectory + "data.txt";//文件路径,AppDomain.CurrentDomain.BaseDirectory为程序所在位置,data.txt为查找的目标文件if (System.IO.File.Exists(path))//查看文件是否存在{    MessageBox.Show("文件存在");}else{    MessageBox.Show("文件不存在");}

判定相应位置下的文件夹是否存在,不存在则创建

//判断相应月份文件夹是否存在,没有则创建string path = AppDomain.CurrentDomain.BaseDirectory + "2016年4月";if (System.IO.Directory.Exists(path)){    MessageBox.Show("存在相应文件夹");}else{    System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(path);    directoryInfo.Create();    MessageBox.Show("不存在相应文件夹,已自动创建");}

配置文件操作

- 添加->常规->应用程序配置文件->得到app.config(不要改名,不然下面读取会出错)
- 在config文件的configuration标签中添加appSettings,整个文件内容如下

<?xml version="1.0" encoding="utf-8" ?><configuration>  <appSettings>    <add key="Enable" value="Yes"/>    <add key="Date" value="2016年4月"/>  </appSettings></configuration>

- 给程序添加引用system.configration.dll,并在需要用到的地方添加命名空间引用

using System.Configuration;

- 在需要查看配置文件的地方用如下代码进行查看

string str = ConfigurationManager.AppSettings["Enable"];//语句返回Enable里面的值给str

- 如果需要修改配置文件里面的值,则用如下的代码进行修改

Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);cfa.AppSettings.Settings["Enable"].Value = "WANGLICHAO";cfa.Save();
1 0
原创粉丝点击