直接打開指定的文件
System.Diagnostics.Process.Start(v_OpenFilePath);
直接打開目錄
string v_OpenFolderPath = @"目錄路徑"; System.Diagnostics.Process.Start("explorer.exe", v_OpenFolderPath);
在WinForm/C#中打開一個文件,主要是用到進程的知識。
下面是一些實例,可以模仿着去實現。
1. 打開文件
private void btOpenFile_Click(object sender, EventArgs e)
{
//定義一個ProcessStartInfo實例
System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
//設置啟動進程的初始目錄
info.WorkingDirectory = Application.StartupPath;
//設置啟動進程的應用程序或文檔名
info.FileName = @"test.txt";
//設置啟動進程的參數
info.Arguments = "";
//啟動由包含進程啟動信息的進程資源
try
{
System.Diagnostics.Process.Start(info);
}
catch (System.ComponentModel.Win32Exception we)
{
MessageBox.Show(this, we.Message);
return;
}
}
2. 打開瀏覽器
private void btOpenIE_Click(object sender, EventArgs e)
{
//啟動IE進程
System.Diagnostics.Process.Start("IExplore.exe");
}
3. 打開指定URL
方法一:
private void btOpenURL_Click(object sender, EventArgs e)
{
//啟動帶參數的IE進程
System.Diagnostics.Process.Start("IExplore.exe", "http://hi.baidu.com/qinzhiyang");
}
方法二:
private void btOpenURLwithArgs_Click(object sender, EventArgs e)
{
//定義一個ProcessStartInfo實例
System.Diagnostics.ProcessStartInfo startInfo = newSystem.Diagnostics.ProcessStartInfo("IExplore.exe");
//設置進程參數
startInfo.Arguments = " http://hi.baidu.com/qinzhiyang ";
//並且使進程界面最小化
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
//啟動進程
System.Diagnostics.Process.Start(startInfo);
}
4. 打開文件夾
private void btOpenFolder_Click(object sender, EventArgs e)
{
//獲取“收藏夾”文件路徑
string myFavoritesPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
//啟動進程
System.Diagnostics.Process.Start(myFavoritesPath);
}
5. 打印文件
private void PrintDoc()
{
//定義一個進程實例
System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
try
{
//設置進程的參數
string myDocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
myProcess.StartInfo.FileName = myDocumentsPath + "\\TxtForTest.txt";
myProcess.StartInfo.Verb = "Print";
//顯示txt文件的所有謂詞
foreach (string v in myProcess.StartInfo.Verbs)
MessageBox.Show(v);
myProcess.StartInfo.CreateNoWindow = true;
//啟動進程
myProcess.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
MessageBox.Show(e.Message + " Check the path." + myProcess.StartInfo.FileName);
}
else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
MessageBox.Show(e.Message + " You do not have permission to print this file.");
}
}
}