File类演示

[cce_cs]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;//引用

namespace FileDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;//设置输出颜色
            try
            {
                Console.WriteLine("Create创建文件");
                string path = @"D:1myluoluo.txt";
                if (File.Exists(path))
                {
                    Console.Write("文件已经存在...是否覆盖?(y/n):");
                    if (Console.ReadLine() == "y")
                    {
                        File.Create(path);
                    }
                }
                else
                {
                    File.Create(path);//"D:1myluoluo.txt"如果名为1的目录不存在也会引发异常!
                }
                Console.ReadKey();

                //Console.WriteLine("Move移动文件");
                //File.Move(path, @"D:1myluoluo1.txt");//不允许覆盖已有的文件
                //Console.ReadKey();

                //Console.WriteLine("Copy复制文件");
                //File.Copy(path, @"D:1myluoluo2.txt");//不允许覆盖已有的文件

                Console.WriteLine("Delete删除文件");
                File.Delete(path);//文件不存在会引发异常
            }
            catch (DirectoryNotFoundException)//目录或者文件不存在时引发的异常
            {
                Console.WriteLine("文件或文件夹不存在,程序终止!");
                Console.ReadKey();
            }
            catch (IOException e)//进行IO操作引发的异常基类
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception ex)//所有异常的基类,通过这个基类,可以捕获上面捕获不到的异常
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    }
}

[/cce_cs]
代码下载:[download id="15"]

5 Replies to “File类演示”

  1. Pingback: C#文件操作 | 笨笨.Blog

回复 落落 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据