C# 新建文本文件

来源:互联网 发布:程序员的工作内容 编辑:程序博客网 时间:2024/05/16 09:04
先引入System.IO的命名空间,然后写如下代码 string file = txtFilePath.Text; string content = txtContent.Text;  if (!File.Exists(file) == true)   {                MessageBox.Show("存在此文件!");            }            else            {                FileStream myFs = new FileStream(file, FileMode.Create);                StreamWriter mySw = new StreamWriter(myFs);                mySw.Write(content);                mySw.Close();                myFs.Close();                MessageBox.Show("写入成功");

}

C#创建txt文件

一、 判断文件是否存在,不存在则创建,存在就往里面写入信息。

         if (!File.Exists("F:\\TestTxt.txt"))            {                FileStream fs1 = new FileStream("F:\\TestTxt.txt", FileMode.Create, FileAccess.Write);//创建写入文件                 StreamWriter sw = new StreamWriter(fs1);                sw.WriteLine(this.textBox3.Text.Trim() + "+" + this.textBox4.Text);//开始写入值                sw.Close();                fs1.Close();            }            else            {                FileStream fs = new FileStream("F:\\TestTxt.txt", FileMode.Open, FileAccess.Write);                StreamWriter sr = new StreamWriter(fs);                sr.WriteLine(this.textBox3.Text.Trim() + "+" + this.textBox4.Text);//开始写入值                sr.Close();                fs.Close();            }

二、创建txt,并往里面填写信息。

       public void CreateFile()        {            FolderBrowserDialog folder = new FolderBrowserDialog();            folder.ShowDialog();            string path = folder.SelectedPath;            string name = "\\" + "aa.txt";            if (!File.Exists(path + name))            {                FileStream fs1 = new FileStream(path + name, FileMode.Create, FileAccess.Write);                StreamWriter sw = new StreamWriter(fs1);                sw.WriteLine("sfsdfdf");//要写入的信息。                 sw.Close();                fs1.Close();                MessageBox.Show("保存成功!");            }        }

0 0