C#打开文件及目录脚本
如果每天开始工作前都要做一些准备工作,比如打开文件或文件夹,我们可以使用代码一键完成。
using System.Diagnostics;
using System.IO;
namespace OpenFile
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
OpenFile.FindFile();
}
}
class OpenFile
{
// 使用原始字符串表示路径
public static string filePath = @"C:\Users\xt_user_6\Desktop\waterRPA3(自动点击)\waterRPA";
public static void FindFile()
{
try
{
// 检查目录是否存在
if (Directory.Exists(filePath))
{
// 获取当前目录下的所有文件
string[] files = Directory.GetFiles(filePath);
//打开当前工作目录窗口
Openfile(filePath);
//遍历文件夹
foreach (string file in files)
{
// 找出符合要求(文件开头包含)的文件
if (Path.GetFileName(file).StartsWith("电气二组") || Path.GetFileName(file).StartsWith("加班申报"))
{
//输出文件名称(如果不使用GetFileName,则是全路径)
Console.WriteLine(Path.GetFileName(file));
//检查文件是否存在
if (File.Exists(file))
{
//打开文件,如果有错误则不成立
if (!Openfile(Path.GetFullPath(file)))
{
//输出错误信息
Console.WriteLine($"打开文件 {Path.GetFileName(file)} 失败!");
}
}
else
{
Console.WriteLine($"文件 {Path.GetFileName(file)} 不存在!");
}
}
}
}
else
{
Console.WriteLine($"目录 {filePath} 不存在!");
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
public static bool Openfile(string fileNameFullPath)
{
try
{
//创建启动示例
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = fileNameFullPath,
UseShellExecute = true
};
Process.Start(startInfo);
return true;
}
catch (Exception ex)
{
Console.WriteLine($"打开失败,遇到错误: {ex.Message}");
return false;
}
}
}
}