当前位置:首页 > C#学习

C#写入文件操作

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

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

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://www.daobk.com/post/107.html

分享给朋友:

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

对象的引用

对象的引用

int、decimal、bool、byte等基础类型(值类型)是传递拷贝;对象(引用类型)则是传递引用。(引用类型包括:类、数组、接口、string)因为基础类型不怎么占内存,而对象则比较占内存。    class Program  &n…

静态成员和静态类

静态成员和静态类

全局变量。static类变量。不用new就能用的方法:static方法,static方法其实就是普通函数在static方法中可以调用其他static成员,但是不能调用非static成员。在非static方法中可以调用static成员。    class&nbs…

索引器

索引器

C#中提供了按照索引器进行访问的方法定义索引器的方式:string this[int index]{get { return ""; }set { }},string为索引器的类型,[]中是参数列表。进行索引器写操作就是调用set代码块,在set内部使用value得到用户设置的值…

图片的显示和隐藏

图片的显示和隐藏

页面上有一张图片(PictureBox,在Image属性中加载图片),默认是隐藏的(Visible=False),用户在文本框中输入身份证号(131226198105223452),点击按钮,如果年龄大于18岁则显示图(Visible=True),否则提示年龄太小。取当前年份:DateTime.No…