如何使用C#查找最近使用浏览器打开的文件
要使用C#查找最近使用浏览器打开的文件,可以通过以下步骤实现:
- 引用System.IO和Microsoft.Win32命名空间。
using System.IO;
using Microsoft.Win32;
- 使用Registry类获取浏览器的注册表路径。
string browserKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
string[] browsers = { "chrome.exe", "firefox.exe", "iexplore.exe", "msedge.exe" }; // 支持的浏览器
string browserPath = string.Empty;
foreach (string browser in browsers)
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(browserKey + browser))
{
if (key != null)
{
browserPath = key.GetValue(string.Empty).ToString();
break;
}
}
}
- 使用Process类执行浏览器的命令行,并将输出重定向到一个文件中。
string tempFilePath = Path.Combine(Path.GetTempPath(), "temp.txt"); // 临时文件路径
using (Process process = new Process())
{
process.StartInfo.FileName = browserPath;
process.StartInfo.Arguments = "about:cache"; // 设置浏览器的命令行参数
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
using (StreamWriter writer = new StreamWriter(tempFilePath))
{
writer.Write(process.StandardOutput.ReadToEnd());
}
process.WaitForExit();
}
- 解析临时文件,获取最近使用的文件路径。
string[] lines = File.ReadAllLines(tempFilePath);
List<string> fileNames = new List<string>();
foreach (string line in lines)
{
if (line.StartsWith("file:"))
{
string fileName = line.Substring(5);
fileNames.Add(fileName);
}
}
// 输出最近使用的文件路径
foreach (string fileName in fileNames)
{
Console.WriteLine(fileName);
}
- 删除临时文件。
File.Delete(tempFilePath);
注意:上述代码仅适用于支持about:cache命令行参数的浏览器,如Chrome、Firefox等。对于不同的浏览器,可能需要使用不同的命令行参数或方法来获取最近使用的文件路径
原文地址: https://www.cveoy.top/t/topic/ineh 著作权归作者所有。请勿转载和采集!