进程系列(三)-进程的基本用法(打开文件示列)

第一步   写一个文件父类:

 public class BaseFile
    {
        public string FilePath { get; set; }

        private string _fileName;

        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }
        public BaseFile() 
        {
        
        }
        public BaseFile(string filePath,string fileName)
        {
            this.FilePath = filePath;
            this.FileName = fileName;
        }

        /// <summary>
        /// 设计一个函数用来打开指定的函数
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public void OpenFile(string filePath, string fileName) 
        {
            ProcessStartInfo psi = new ProcessStartInfo(filePath+"//"+fileName);

            Process pro = new Process();

            pro.StartInfo = psi;

            pro.Start();
        }
    }

第二步   分别新建一个TXT,PDF,XLS文件子类继承文件父类:

TXT:

public class TextFile : BaseFile
    {
        public TextFile(string filePath, string fileName)
            : base(filePath,fileName)
        {

        }
    }

PDF:

public class PdfFile : BaseFile
    {
        public PdfFile(string filePath, string fileName)
            : base(filePath, fileName)
        {

        }
    }

XLS:

 public class XlsFile : BaseFile
    {
        public XlsFile(string filePath, string fileName)
            : base(filePath, fileName)
        {

        }
    }

第三步 通过简单工厂模式返回设计父类:

 public class Common
    {
        public static BaseFile GetFile(string filePath,string fileName) 
        {
            string strExtension = Path.GetExtension(fileName);

            BaseFile bf = null;

            switch (strExtension)
            {
                case ".txt":
                    bf = new TextFile(filePath, fileName);
                    break;
                case ".pdf":
                    bf = new PdfFile(filePath, fileName);
                    break;
                case ".xls":
                    bf = new XlsFile(filePath, fileName);
                    break;
            }

            return bf;
        }
    }

第四步   从控制台操作要打开的文件:

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入你要打开文件的路径:");
            string filePath = Console.ReadLine();
            Console.WriteLine("请输入你要开文件的名字:");
            string fileName = Console.ReadLine();

            //通过简单工厂模式返回设计父类
            BaseFile bf = Common.GetFile(filePath, fileName);

            if (bf!=null)
            {
                bf.OpenFile(filePath, fileName);
            }

            Console.ReadKey();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_26347097/article/details/81436648