在WinForm/C#中打開一個文件,主要是用到進(jìn)程的知識。 下面是一些實例,可以模仿著去實現(xiàn)。 1. 打開文件 private void btOpenFile_Click(object sender, EventArgs e) { //定義一個ProcessStartInfo實例 System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); //設(shè)置啟動進(jìn)程的初始目錄 info.WorkingDirectory = Application.StartupPath; //設(shè)置啟動進(jìn)程的應(yīng)用程序或文檔名 info.FileName = @"test.txt"; //設(shè)置啟動進(jìn)程的參數(shù) info.Arguments = ""; //啟動由包含進(jìn)程啟動信息的進(jìn)程資源 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進(jìn)程 System.Diagnostics.Process.Start("IExplore.exe"); } 3. 打開指定URL 方法一: private void btOpenURL_Click(object sender, EventArgs e) { //啟動帶參數(shù)的IE進(jìn)程 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"); //設(shè)置進(jìn)程參數(shù) startInfo.Arguments = " http://hi.baidu.com/qinzhiyang "; //并且使進(jìn)程界面最小化 startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized; //啟動進(jìn)程 System.Diagnostics.Process.Start(startInfo); } 4. 打開文件夾 private void btOpenFolder_Click(object sender, EventArgs e) { //獲取“收藏夾”文件路徑 string myFavoritesPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Favorites); //啟動進(jìn)程 System.Diagnostics.Process.Start(myFavoritesPath); } 5. 打印文件 private void PrintDoc() { //定義一個進(jìn)程實例 System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); try { //設(shè)置進(jìn)程的參數(shù) 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; //啟動進(jìn)程 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."); } } }
|
|
來自: 昵稱16756252 > 《c#》