1、通过进程打开本地文件
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01语法复习
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo(@"C:\Users\Administrator\Desktop\记录.txt");
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
}
2、使用抽象类打开本地文件
- 抽象出父类,要打开的文件类型:txt,wmv,jpg;
public abstract class FilePath
{
public abstract void OpenFile();
}
- 创建子类,继承父类,并重写抽象方法;
public class TxtFiel : FileFather
{
public override void OpenFile()
{
ProcessStartInfo psi = new ProcessStartInfo(文件全路径 );
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
- 通过进程打开文件,需要文件的全路径,所以需要传入文件的全路径。在父类创建全路径的字段,并封装;
public abstract class FileFather
{
string _fullPath;
public FileFather(string fullPath)
{
this.FullPath = fullPath;
}
public string FullPath { get => _fullPath; set => _fullPath = value; }
public abstract void OpenFile();
}
- 子类生成构造函数,并继承父类的fullPath属性;
public class TxtFiel : FileFather
{
public TxtFiel(string fullPath) : base(fullPath)
{
}
public override void OpenFile()
{
ProcessStartInfo psi = new ProcessStartInfo(this.FullPath);
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
- 同理,创建另外两个子类
public class JpgFile : FileFather
{
public JpgFile(string fullPath) : base(fullPath)
{
}
public override void OpenFile()
{
ProcessStartInfo psi = new ProcessStartInfo(this.FullPath);
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
public class WmvFile : FileFather
{
public WmvFile(string fullPath) : base(fullPath)
{
}
public override void OpenFile()
{
ProcessStartInfo psi = new ProcessStartInfo(this.FullPath);
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
- 书写静态函数,通过简单工厂模式创建子类对象并里氏转化给父类,返回一个父类
public static FileFather GetFile(string fileName, string fullName)
{
FileFather ff = null;
string extension = Path.GetExtension(fileName);
switch (extension)
{
case ".txt":
ff = new TxtFiel(fullName);
break;
case ".jpg":
ff = new TxtFiel(fullName);
break;
case ".wmv":
ff = new TxtFiel(fullName);
break;
}
return ff;
}
- 创建父类对象,通过父类对象调用父类方法,通过父类方法调用子类方法。
Console.WriteLine("请输入要打开的文件路径");
string path = Console.ReadLine();
Console.WriteLine("请输入要打开的文件名");
string fileName = Console.ReadLine();
FileFather ff = GetFile(fileName, path + fileName);
ff.OpenFile();
总结fullName参数的传动:
获取fullName字符串——>传入GetFile方法,子类创建对象,通过构造函数将fullName 传入子类fullPaht,赋值父类字段和属性_fullPath和FullPath,最后调用OpenFile方法,调用FullPath参数,完成打开文件。