当前位置:首页 > C#学习 > 正文内容

C#写入文件操作

小道7年前 (2018-10-30)C#学习6074

在当前目录创建一个文本文档,并写入文本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace IO写入文件
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入一个文件名:");//提示输入一个文件名
            string FILE_NAME = Console.ReadLine();//输入文件名
            FILE_NAME += ".txt";//文件名后加上 .txt
            if (File.Exists(FILE_NAME))//判断文本文档是否存在
            {
                Console.WriteLine("你输入的文件名已存在.");//如果存在,则提示
                Console.ReadKey();//按任意键继续
                return;//退出
            }

            FileStream fs = new FileStream(FILE_NAME,FileMode.Create);//如不存在,则创建新的文本文档
            BinaryWriter w = new BinaryWriter(fs);//创建写入
            w.Write("\r\n 小道博客");//写入
            w.Write("\r\n http://www.daobk.com");//写入
            Console.WriteLine("写入成功!");//提示
            w.Close();//关闭
            fs.Close();//关闭
            Console.ReadKey();//按任意键继续
        }
    }
}

输出结果:

image.pngimage.png

image.png


使用方法调用写入文本文档:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IO写入
{
    class Program
    {
        static void Main(string[] args)
        {
            using (StreamWriter w = File.AppendText("test.txt"))//打开或创建一个文本文档 并且写入
            {
                Log("小道博客",w);//调用方法
                Log("http://www.daobk.com",w);//调用方法
                Console.WriteLine("写入成功!");//提示
                Console.ReadKey();//按任意键
                w.Close();//关闭当前的 StreamWriter 对象和基础流。
            }
        }
        public static void Log(string logMessage, TextWriter w)//全局 静态 写入方法
        {
            w.WriteLine("你输入的是:{0}",logMessage);//将传递过来的字符串写入到文本
            w.Flush();//清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。
        }
    }
}

输出结果:

image.pngimage.png

扫描二维码推送至手机访问。

版权声明:本文由小道发布,如需转载请注明出处。

本文链接:https://daobk.com/post/107.html

分享给朋友:

“C#写入文件操作” 的相关文章

数组:将一个字符串数组输出为|分割的形式

数组:将一个字符串数组输出为|分割的形式

数组:将一个字符串数组输出为|分割的形式,比如“王钢蛋|李铁蛋|铁锤”            string[] s = { "王钢...

面向对象概念

面向对象概念

面向对象不是取代面向过程的。类、对象。“人”是类,“张三”是“人”这个类的对象。类是抽象的,对象是具体的。按钮就是类,某个按钮就是对象。对象可以叫做类的实例(Instance)。类就像int,对象就像10。字段Field(和某个对象相关的变量),字段就是类的状态。人这个类有姓名、年龄、身高等字段。类...

命名空间namespace

命名空间namespace

namespace(命名空间),用于解决类重名问题,可以看做“类的文件夹”。在代码中使用其他类的时候需要using类所在的namespace。System.Collections.ArrayList,快速引入的方法,右键→解析(Ctrl+.)。为什么使用Convert、Console等类不需要自己写...

输入Email地址,输出用户名和域名。

输入Email地址,输出用户名和域名。

输入Email地址,输出用户名和域名。        private void button1_Click(object sender, EventArgs e)//按钮...