WPF的文件读写保存操作示例

包含打开文件,保存文件,文件读取选择对话框,文件保存选择对话框。



1.打开指定位置的文件,如果文件存在则覆盖



public void createFile()
        {
            fileCount++;
            System.DateTime currentTime = new System.DateTime();
            currentTime = DateTime.Now;
            string path = "./Test";
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("//Code created by ImageGoLCD at "+currentTime);
            sw.Flush();
            sw.Close();
            fs.Close();
            
        }






2.打开文件,寻找末尾并将数据添加到末尾


 public void writeFile(string str)
        {
            string path = "./tempCode" + fileCount + ".txt";
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(str);
            sw.Flush();
            sw.Close();
            fs.Close();
        }


3.调用windows的文件打开对话框打开图片文件


var openFileDialog = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "*.jpg,*.jpeg,*.bmp,*.jif,*.ico,*.png,*.tif,*.wmf|*.jpg;*.jpeg;*.bmp;*.gif;*.ico;*.png;*.tif;*.wmf"
            };
            var result = openFileDialog.ShowDialog();
            if (result == true)
            {
                path = openFileDialog.FileName;//传入选择的文件路径到path中
            }



4.调用windows的文件保存对话框保存txt格式文件,如果文件存在覆盖这个文件 



var saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                        saveFileDialog.Filter = "TXT File(*.txt)|*.txt";
                        var result = saveFileDialog.ShowDialog();
                        if (result == true)
                        {

                            FileStream savefs = new FileStream(saveFileDialog.FileName, FileMode.Create);
                            StreamWriter savesw = new StreamWriter(savefs);
                            savesw.Flush();
                            savesw.Close();
                        }




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值