【学习笔记】C#文件流联系|读取文件、追加Txt

来源:互联网 发布:ubuntu设置root密码 编辑:程序博客网 时间:2024/05/19 02:04
             //读取文件 方式1
            string filePath = HttpRuntime.AppDomainAppPath + "/Resource/File/filetest.txt";

            FileStream file = new FileStream(filePath, FileMode.Open);
            StreamReader sr = new StreamReader(file);

            string result = sr.ReadToEnd();
            sr.Close();

            /*=========================================*/
            //读取文件 方式2
            StreamReader sr2 = new StreamReader(filePath, Encoding.UTF8);
            string result2 = sr2.ReadToEnd();
            sr2.Close();

            /*=========================================*/
            //遍历文件每一行
            StreamReader sr3 = new StreamReader(filePath, Encoding.Default);
            string str = sr3.ReadLine();

            while (str != null)
            {
                //处理str
                str = sr3.ReadLine();
            }

            sr3.Close();

            /*=========================================*/
            //追加内容到txt
            StreamWriter sw = new StreamWriter(filePath, true, Encoding.Default);
            sw.WriteLine("追加内容");
            sw.Close();

            /*=========================================*/
            //判断文件是否存在
            if (System.IO.File.Exists(filePath))
            {
                string isexist = "";
            }
           
            //判断目录是否存在
            string filePath3 = HttpRuntime.AppDomainAppPath + "/Resource/File";
            if (Directory.Exists(filePath3))
            {
                string isexist = "";
            }
原创粉丝点击