C# Winform调用Word等
在C# Winform打开Word,Excel,Txt,PDF 等文档时,直接调用计算机上的已安装软件,若没有安装,则提示信息。此方法是最简单的一种,不用在C#内部嵌入编辑器。可适应多种类型的文档。
代码如下:
/// <summary> /// 附件上传 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.FileName = ""; //打开文件窗口筛选器 ofd.Filter = "Word&图片&PDF|*.doc;*.docx;*.jpg;*.jpeg;*.bmp;*.png;*.gif|Word|*.doc;*.docx|图片|*.jpg;*.jpeg;*.bmp;*.png;*.gif|PDF|*.pdf"; //读取文档 if (ofd.ShowDialog() != DialogResult.OK) return; string path = ofd.FileName; //设置文件夹只读 //System.IO.DirectoryInfo DirInfo = new DirectoryInfo("filepath"); //DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory; //设置文件的只读属性 if (File.GetAttributes(path) != FileAttributes.ReadOnly) System.IO.File.SetAttributes(path, System.IO.FileAttributes.ReadOnly); try { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = true; p.StartInfo.FileName = path; p.Start(); // 或一行代码:System.Diagnostics.Process.Start(path); } catch (Exception ee) { string filetype = path.Substring(path.LastIndexOf('.')); string message = ""; switch (filetype.ToLower()) { case ".doc": message = "请安装office( word)2003及以上版本软件!"; break; case ".docx": message = "请安装office( word)2007及以上版本软件!"; break; case ".pdf": message = "请安装PDF阅读器!"; break; case ".png": case ".bmp": case ".gif": case ".jpeg": case ".jpg": message = "请安装图片阅读器!"; break; default: message = "请安装合适的阅读器!"; break; } MessageBox.Show(ee.Message + "\n若要打开附件:" + path.Substring(path.LastIndexOf('\\') + 1) + "\n" + message, "打开出错", MessageBoxButtons.OK, MessageBoxIcon.Error); } }