C#中读取文件

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

namespace ReadFile
{
    class Programs
    {
        static void Main(string[] args)
        {
            Console.WriteLine("請輸入要讀取的文件:");
            //读取输入文件名
            string fileName = Console.ReadLine();
            //分割线
            Console.WriteLine("*******************************");
            //输入文件路径
            string filePath = "D://txts//";
            //输入文件路径与文件名进行拼接
            string filePathAndName = filePath + fileName;
            //判断该文件是否存在
            if (File.Exists(filePathAndName))
            {
                //如果存在,读取文件内容
                string textFile = File.ReadAllText(filePathAndName, Encoding.Default);
                Console.WriteLine(textFile);
            }
            else
            {
                //如果不存在则提示文件不存在
                Console.WriteLine(filePathAndName + "該文件不存在,請檢查輸入的文件名是否正確!");
            }
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37954004/article/details/80691809