平时经常会碰到一个情况,打开浏览器访问了一堆页面,突然遇到什么事情需要重启电脑,或者关闭掉浏览器,这时候比较尴尬,可能刚刚打开的这些页面还没有全部看完,或者都是一些参考性的网站需要保留,那怎么办?把所有浏览的页面的URL贴到一个txt里面?要是打开的就只有一两个页面,那还好,要是打开了一排页面,那就惨了。下面这个小程序就是用来帮助我们将当前打开的IE浏览器的所有页面保存下来,等我们需要恢复页面的时候,再一键还原回来。用处不再赘述,直接贴代码:
public partial class IE_Recover : Form
{
private const string protectedFileName = "IE_Recover.dat";
private object m = Type.Missing;
private enum BrowserNavConstants
{
/// <summary>
/// Open the resource or file in a new window.
/// </summary>
navOpenInNewWindow = 0x1,
/// <summary>
/// Do not add the resource or file to the history list. The new page replaces the current page in the list.
/// </summary>
navNoHistory = 0x2,
/// <summary>
/// Do not consult the Internet cache; retrieve the resource from the origin server (implies BINDF_PRAGMA_NO_CACHE and BINDF_RESYNCHRONIZE).
/// </summary>
navNoReadFromCache = 0x4,
/// <summary>
/// Do not add the downloaded resource to the Internet cache. See BINDF_NOWRITECACHE.
/// </summary>
navNoWriteToCache = 0x8,
/// <summary>
/// If the navigation fails, the autosearch functionality attempts to navigate common root domains (.com, .edu, and so on). If this also fails, the URL is passed to a search engine.
/// </summary>
navAllowAutosearch = 0x10,
/// <summary>
/// Causes the current Explorer Bar to navigate to the given item, if possible.
/// </summary>
navBrowserBar = 0x20,
/// <summary>
/// Microsoft Internet Explorer 6 for Microsoft Windows XP Service Pack 2 (SP2) and later. If the navigation fails when a hyperlink is being followed, this constant specifies that the resource should then be bound to the moniker using the BINDF_HYPERLINK flag.
/// </summary>
navHyperlink = 0x40,
/// <summary>
/// Internet Explorer 6 for Windows XP SP2 and later. Force the URL into the restricted zone.
/// </summary>
navEnforceRestricted = 0x80,
/// <summary>
/// Internet Explorer 6 for Windows XP SP2 and later. Use the default Popup Manager to block pop-up windows.
/// </summary>
navNewWindowsManaged = 0x0100,
/// <summary>
/// Internet Explorer 6 for Windows XP SP2 and later. Block files that normally trigger a file download dialog box.
/// </summary>
navUntrustedForDownload = 0x0200,
/// <summary>
/// Internet Explorer 6 for Windows XP SP2 and later. Prompt for the installation of Microsoft ActiveX controls.
/// </summary>
navTrustedForActiveX = 0x0400,
/// <summary>
/// Windows Internet Explorer 7. Open the resource or file in a new tab. Allow the destination window to come to the foreground, if necessary.
/// </summary>
navOpenInNewTab = 0x0800,
/// <summary>
/// Internet Explorer 7. Open the resource or file in a new background tab; the currently active window and/or tab remains open on top.
/// </summary>
navOpenInBackgroundTab = 0x1000,
/// <summary>
/// Internet Explorer 7. Maintain state for dynamic navigation based on the filter string entered in the search band text box (wordwheel). Restore the wordwheel text when the navigation completes.
/// </summary>
navKeepWordWheelText = 0x2000
}
public IE_Recover()
{
InitializeComponent();
}
private string GetApplicationDataDir()
{
return Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
}
private string GetProtectedFileDir()
{
return Path.Combine(GetApplicationDataDir(), "IE_Recover");
}
private string GetProtectedFilePath()
{
return Path.Combine(GetProtectedFileDir(), protectedFileName);
}
private void CreateDataFile()
{
if (!Directory.Exists(GetProtectedFileDir()))
{
Directory.CreateDirectory(GetProtectedFileDir());
}
using (File.Create(GetProtectedFilePath())) { }
}
// true if data file exists and contains data, otherwise false
private bool CheckDataFile()
{
string protectedFilePath = GetProtectedFilePath();
if (!File.Exists(protectedFilePath))
{
CreateDataFile();
return false;
}
using (Stream fs = new FileStream(protectedFilePath, FileMode.Open))
{
byte[] buf = new byte[1];
int len = fs.Read(buf, 0, 1);
return len == 1;
}
}
private List<string> GetURLsFromOpenedIESessions()
{
try
{
List<string> results = new List<string>();
SHDocVw.InternetExplorer browser;
string myLocalLink;
mshtml.IHTMLDocument2 myDoc;
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
string filename;
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if ((filename == "iexplore"))
{
browser = ie;
myDoc = browser.Document;
myLocalLink = myDoc.url;
results.Add(myLocalLink);
}
}
return results;
}
catch
{
return null;
}
}
private string StringToBase64(string s)
{
byte[] buf = Encoding.Default.GetBytes(s);
return Convert.ToBase64String(buf);
}
private string Base64ToString(string s)
{
byte[] buf = Convert.FromBase64String(s);
return Encoding.Default.GetString(buf);
}
private void WriteUrlsToDataFile(List<string> urls)
{
using (Stream fs = new FileStream(GetProtectedFilePath(), FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string url in urls)
{
sw.WriteLine(StringToBase64(url));
}
}
}
}
private List<string> ReadUrlsFromDataFile()
{
if (CheckDataFile())
{
List<string> urls = new List<string>();
using (Stream fs = new FileStream(GetProtectedFilePath(), FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
string url = Base64ToString(sr.ReadLine());
urls.Add(url);
}
}
}
return urls;
}
return null;
}
private List<string> ReadLinesFromFile(string filePath)
{
List<string> lines = new List<string>();
using (Stream fs = new FileStream(filePath, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
}
}
return lines;
}
private void WriteLinesToFile(List<string> lines, string filePath)
{
using (Stream fs = new FileStream(filePath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string line in lines)
{
sw.WriteLine(line);
}
}
}
}
private InternetExplorer openNewInternetExplorerInstance(string url)
{
InternetExplorer ie = new InternetExplorer();
ie.Navigate2(url, ref m, ref m, ref m, ref m);
ie.Visible = true;
return ie;
}
private void openNewInternetExplorerTab(ref InternetExplorer ie, string url)
{
ie.Navigate2(url, BrowserNavConstants.navOpenInNewTab, ref m, ref m, ref m);
ie.Visible = true;
}
private bool WriteToDataFileCheck()
{
if (CheckDataFile())
{
DialogResult opt = MessageBox.Show("Data exists, do you want to overwrite?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (opt == DialogResult.No)
{
return false;
}
}
return true;
}
private void Backup_Click(object sender, EventArgs e)
{
if (WriteToDataFileCheck())
{
WriteUrlsToDataFile(GetURLsFromOpenedIESessions());
MessageBox.Show("All opened [IE]Urls saved");
}
}
private void Recover_Click(object sender, EventArgs e)
{
if (CheckDataFile())
{
List<string> urls = ReadUrlsFromDataFile();
if (urls != null)
{
InternetExplorer ie = openNewInternetExplorerInstance(urls[0]);
int len = urls.Count;
for (int i = 1; i < len; i++)
{
openNewInternetExplorerTab(ref ie, urls[i]);
}
}
}
}
private string OpenFile(bool checkFileExist)
{
OpenFileDialog open = new OpenFileDialog();
open.AddExtension = true;
open.Multiselect = false;
open.Title = "Select a file";
open.CheckFileExists = checkFileExist;
open.Filter = "* (*.*)|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
return open.FileName;
}
else
{
return string.Empty;
}
}
private void Import_Click(object sender, EventArgs e)
{
string fileName = OpenFile(true);
if (string.IsNullOrEmpty(fileName))
{
return;
}
try
{
if (WriteToDataFileCheck())
{
WriteUrlsToDataFile(ReadLinesFromFile(fileName));
MessageBox.Show("Import succeeded");
}
}
catch
{
MessageBox.Show("Failed to import from file, file content should be like:\r\n<url>\r\n<url>\r\n<url>\r\n<url>");
}
}
private void Export_Click(object sender, EventArgs e)
{
string fileName = OpenFile(false);
if (string.IsNullOrEmpty(fileName))
{
return;
}
try
{
WriteLinesToFile(ReadUrlsFromDataFile(), fileName);
MessageBox.Show("Export succeeded");
}
catch (Exception err)
{
MessageBox.Show(string.Format("Failed to export, error msg: {0}", err.Message));
}
}
private void Help_Click(object sender, EventArgs e)
{
MessageBox.Show("Usage:\r\nUse [Protect] to backup Urls in opened IE sessions\r\nUse [Recover] to recover the IE pages from the backup\r\nUse [Import] to import Urls from a file\r\nUse [Export] to export protected Urls", "HELP");
}
}
WinForm上面拖了5个Button,名称和显示的相同: