• 【Coding】C# 操作文件(一)


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

    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("输入已存目录");
                string sBaseDir = Console.ReadLine();
                FileAndFileInfo.ListFile(sBaseDir);
                Console.Read();
                Console.WriteLine("输入创建目录");
                string sNewFile = Console.ReadLine();

                FileAndFileInfo.CreateFile(sNewFile);
                Console.ReadLine();
                FileAndFileInfo.ReadFile(sNewFile);
                Console.ReadLine();
                FileAndFileInfo.DeleteFile(sNewFile);
                Console.WriteLine();
            }


        }

        class FileAndFileInfo
        {
            public static void ListFile(string sDir)
            {
                if (Directory.Exists(sDir))
                {
                    DirectoryInfo di = new DirectoryInfo(sDir);
                    Console.WriteLine("文件创建时间\t\t文件名\t\t\t文件大小");
                    foreach (FileInfo file in di.GetFiles())
                    {
                        Console.WriteLine(string.Format("{0}\t{1}\t{2}", file.CreationTime, file.Name, file.Length));
                    }
                }
                else
                {
                    Console.WriteLine("文件{0}不存在",sDir);
                }

           
            }

            public static void CreateFile(string sFile)
            {
                FileStream fs = File.Create(sFile);
                StreamWriter sw = new StreamWriter(fs);
                Console.WriteLine("输入文本内容:");
                string str = Console.ReadLine();
                sw.WriteLine(str);
                sw.Close();
                fs.Close();
                Console.WriteLine(string.Format("创建文本文件{0}",sFile));
            }

            public static void ReadFile(string sFile)
            {
                string str = "";
                StreamReader sr = new StreamReader(sFile);
                str = sr.ReadToEnd();
                sr.Close();
                Console.WriteLine(string.Format("读取文本文件{0}",str));
            }
            public static void DeleteFile(string sFile)
            {
                File.Delete(sFile);
                Console.WriteLine(string.Format("删除文件{0}", sFile));
            }


        }
    }

  • 相关阅读:
    2016-02-24 工作日记
    金字塔培训
    你找到自己的路了么?
    你是个成熟的职场人么?
    码农十年总结
    码农十年连载六
    码农十年连载五
    码农十年连载四
    码农十年连载三
    码农十年连载二
  • 原文地址:https://www.cnblogs.com/cuishao1985/p/1747226.html
Copyright © 2020-2023  润新知