public static void ProcessMsgList(string[] files) { foreach (string filename in files) { if (IsMsgFile(filename)) { OutlookStorage.Message message = new OutlookStorage.Message(filename); DateTime date = message.ReceivedOrSentTime; message.Dispose(); AddDateToMsgName(filename, date); } } }
private void ReadMsgFile(string msgfile) { //清空附件内容列表,删除附件菜单项 MailBody = string.Empty; Attachments.Clear(); btnFiles.DropDownItems.Clear(); lblStatus.Text = "-"; FileInfo fi = new FileInfo(msgfile); this.Text = string.Format("EmailViewer of {0}", fi.Name); using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read)) { //fileName = string.Empty; OutlookStorage.Message message = new OutlookStorage.Message(messageStream); messageStream.Close(); try { //获取comment# //Comment has been added as: 34227 //string comment = null; MailBody = message.BodyText; this.txtMail.Text = MailBody; //附件 if (message.Attachments.Count > 0) { int i = 0; foreach (OutlookStorage.Attachment item in message.Attachments) { string fileContent = System.Text.Encoding.UTF8.GetString(item.Data); Attachments.Add(fileContent); ToolStripMenuItem ddItem = new ToolStripMenuItem(item.Filename); ddItem.Name = "btnFile" + i.ToString(); ddItem.Width = 300; ddItem.Click += ddItem_Click; btnFiles.DropDownItems.Add(ddItem); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "不好,出了点儿问题", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { message.Dispose(); } } }
private void readFile(String filename) { txtBox.Clear(); treeView.Nodes.Clear(); Stream messageStream = File.Open(filename, FileMode.Open, FileAccess.Read); OutlookStorage.Message message = new OutlookStorage.Message(messageStream); messageStream.Close(); if (!isOutlookMessage(message)) { MessageBox.Show("No Outlook MSG file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); message.Dispose(); return; } smimefound = false; this.loadMessage(message, treeView.Nodes.Add("Message")); message.Dispose(); mnuExport.Enabled = true; treeView.ExpandAll(); txtBox.SelectionStart = 0; txtBox.SelectionLength = 0; copyContentToClipboardToolStripMenuItem.Enabled = true; }
private void btnDump_Click(object sender, EventArgs e) { this.openFileDialog1.Multiselect = true; DialogResult msgFileSelectResult = this.openFileDialog1.ShowDialog(); if (msgFileSelectResult == DialogResult.OK) { string targetFolder = this.openFileDialog1.FileNames[0]; targetFolder = System.IO.Directory.GetParent(targetFolder).FullName; foreach (string msgfile in this.openFileDialog1.FileNames) { bool attachGenerated = false; string fileName = null; using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read)) { fileName = string.Empty; OutlookStorage.Message message = new OutlookStorage.Message(messageStream); messageStream.Close(); try { //获取comment# //Comment has been added as: 34227 string comment = null; string body = message.BodyText; comment = body.Substring(body.IndexOf("Comment has been added as:") + 26).Trim(); //Insurer: Aggressive Insurance Texas Elite string insurer = null; string state = null; string title = message.Subject; if (title.Contains("Reminder Email for debugging purpose")) { //CarrierName: Progressive Auto insurer = ExtractHtml(body, "CarrierName:", "\r\n"); if (string.IsNullOrEmpty(insurer)) { throw new Exception("Failed to extract CarrierName"); } insurer = insurer.Trim().Split(' ')[0]; //Quoting State: VT state = body.Substring(body.IndexOf("Quoting State:") + 14).Trim(); state = state.Substring(0, state.IndexOf("\r\n")); } else { //insurer = body.Substring(body.IndexOf("Insurer:")+8).Trim(); //insurer = insurer.Substring(0, insurer.IndexOf("\r\n")); //insurer = insurer.Substring(0, insurer.IndexOf(" ")); //qpquote\stdInsurers\HartfordScrape.vb insurer = body.Substring(body.LastIndexOf("qpquote\\stdInsurers\\") + 20); if (insurer.Contains(".vb")) { insurer = insurer.Substring(0, insurer.IndexOf(".vb")); if (insurer.Contains("Scrape")) { //insurer = insurer.Replace("Scrape", ""); insurer = insurer.Substring(0, insurer.IndexOf("Scrape")); } } else { //Insurer: Progressive Insurance Company insurer = ExtractHtml(insurer, "Insurer:", "Insurer Web Login:"******"Failed to extract Insurer Company Name"); } insurer = insurer.Trim().Split(' ')[0]; } //State Quoted: MA state = body.Substring(body.IndexOf("State Quoted:") + 13).Trim(); state = state.Substring(0, state.IndexOf("\r\n")); } //2017-08-10,iimax:state rule changed if (state.StartsWith("State")) { state = state.Substring(5); } fileName = string.Format("#{0}-{1} ({2}).txt", comment, insurer, state); //附件 if (message.Attachments.Count > 0) { OutlookStorage.Attachment file = message.Attachments[0]; string fileContent = System.Text.Encoding.UTF8.GetString(file.Data); //2016-06-29:修改last name为 testing,修改 effdate System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(fileContent); if (fileContent.Contains("<AutoQuote>")) { var CusLastName = doc.DocumentElement.SelectSingleNode("/AutoQuote/Quotation/CusLastName"); if (CusLastName != null) { //Create a comment. XmlComment newComment = doc.CreateComment(CusLastName.OuterXml); CusLastName.ParentNode.InsertAfter(newComment, CusLastName); CusLastName.InnerText = "Testing"; } var EffDate = doc.DocumentElement.SelectSingleNode("/AutoQuote/Quotation/EffDate"); if (EffDate != null) { string eff = EffDate.InnerText; DateTime dt = DateTime.Today; DateTime.TryParse(eff, out dt); if (dt < DateTime.Today) { XmlComment newComment = doc.CreateComment(EffDate.OuterXml); EffDate.ParentNode.InsertAfter(newComment, EffDate); EffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy"); } } var drivers = doc.DocumentElement.SelectNodes("/AutoQuote/Quotation/Drivers/Driver"); if (drivers != null) { foreach (XmlNode item in drivers) { var LastName = item.SelectSingleNode("LastName"); if (LastName != null) { XmlComment newComment = doc.CreateComment(LastName.OuterXml); LastName.ParentNode.InsertAfter(newComment, LastName); LastName.InnerText = "Testing"; } } } } else if (fileContent.Contains("<HomeQuote>")) { var CusLastName = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/CusLastName"); if (CusLastName != null) { //Create a comment. XmlComment newComment = doc.CreateComment(CusLastName.OuterXml); CusLastName.ParentNode.InsertAfter(newComment, CusLastName); CusLastName.InnerText = "Testing"; } var hEffDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/hEffDate"); if (hEffDate != null) { string eff = hEffDate.InnerText; DateTime dt = DateTime.Today; if (DateTime.TryParse(eff, out dt)) { } if (dt < DateTime.Today) { XmlComment newComment = doc.CreateComment(hEffDate.OuterXml); hEffDate.ParentNode.InsertAfter(newComment, hEffDate); hEffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy"); var hExpDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/hExpDate"); if (hExpDate != null) { XmlComment hExpDateComment = doc.CreateComment(hExpDate.OuterXml); hExpDate.ParentNode.InsertAfter(hExpDateComment, hExpDate); hExpDate.InnerText = DateTime.Today.AddYears(1).ToString("MM/dd/yyyy"); } //修改 RiskInfo var EffDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/RiskInfo/ThisRisk/EffDate"); var ExpDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/RiskInfo/ThisRisk/ExpDate"); if (EffDate != null) { XmlComment xComment = doc.CreateComment(EffDate.OuterXml); EffDate.ParentNode.InsertAfter(xComment, EffDate); EffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy"); } if (ExpDate != null) { XmlComment xComment = doc.CreateComment(ExpDate.OuterXml); ExpDate.ParentNode.InsertAfter(xComment, ExpDate); ExpDate.InnerText = DateTime.Today.AddYears(1).ToString("MM/dd/yyyy"); } } } } fileContent = doc.OuterXml; System.IO.File.WriteAllText(Path.Combine(targetFolder, fileName), fileContent); } attachGenerated = true; //MessageBox.Show(fileName); } catch (Exception) { throw; } finally { message.Dispose(); } if (attachGenerated) { //重命名msg FileInfo fi = new FileInfo(msgfile); //目标文件名 string msgfileName = fi.Name; string ourfileName = fi.Name.Replace(".msg", string.Format("{0}.msg", fileName)); ourfileName = ourfileName.Replace("comment#", "#").Replace(".txt.", "."); System.IO.File.Move(msgfile, Path.Combine(fi.DirectoryName, ourfileName)); } } } } }
private void ReadMsgFile(string msgfile) { MessageFile = msgfile; //清空附件内容列表,删除附件菜单项 MailBody = string.Empty; Attachments.Clear(); btnFiles.DropDownItems.Clear(); lblStatus.Text = "-"; FileInfo fi = new FileInfo(msgfile); this.Text = string.Format("EmailViewer of {0}", fi.Name); try { using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read)) { //fileName = string.Empty; OutlookStorage.Message message = new OutlookStorage.Message(messageStream); messageStream.Close(); try { //获取comment# //Comment has been added as: 34227 //string comment = null; MailBody = message.BodyRTF; //附件 string attachments = ""; if (message.Attachments.Count > 0) { int i = 0; foreach (OutlookStorage.Attachment item in message.Attachments) { //string fileContent = System.Text.Encoding.UTF8.GetString(item.Data); Attachments.Add(i); ToolStripMenuItem ddItem = new ToolStripMenuItem(item.Filename); ddItem.Name = "btnFile" + i.ToString(); ddItem.Width = 300; ddItem.Click += ddItem_Click; btnFiles.DropDownItems.Add(ddItem); attachments += String.Format("\t{0}{1}", item.Filename, Environment.NewLine); } } string recipients = ""; foreach (OutlookStorage.Recipient recipeint in message.Recipients) { recipients += String.Format("\t{0} <{1}>{2}", recipeint.DisplayName, recipeint.Email, Environment.NewLine); } MessageMetadata = String.Format(@"Filename: {4} Subject: {0} From: {1} Recipients: {2} Attachments: {3}", message.Subject, message.From, recipients, attachments, fi.Name); this.txtMail.Rtf = MailBody; } catch (IOException ex) { MessageBox.Show(ex.Message, "Exeception opening the email!", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { message.Dispose(); } } } catch (IOException ex) { MessageBox.Show(ex.Message, "Couldn't open file", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void ddItem_Click(object sender, EventArgs e) { ToolStripMenuItem ddItem = sender as ToolStripMenuItem; if (ddItem == null) { return; } string btnName = ddItem.Name; int idx = ddItem.Name.IndexOf("btnFile"); if (idx == -1) { lblStatus.Text = "Error"; return; } string AttachIndex = ddItem.Name.Substring(idx + 7); int? index = ToInt(AttachIndex); if (index.HasValue && MessageFile != null) { int attachmentNum = Attachments[index.Value]; try { using (Stream messageStream = File.Open(MessageFile, FileMode.Open, FileAccess.Read)) { //fileName = string.Empty; OutlookStorage.Message message = null; try { message = new OutlookStorage.Message(messageStream); //messageStream.Close(); int i = 0; OutlookStorage.Attachment attachment = null; foreach (OutlookStorage.Attachment attachment_ in message.Attachments) { if (i == attachmentNum) { attachment = attachment_; break; } } if (attachment == null) { MessageBox.Show("Something has gone terribly wrong in opening this attachment (can't find it attached anymore)"); return; } string filename = String.Format("{0}{1}{2}", TempPath, Path.DirectorySeparatorChar, attachment.Filename); using (FileStream f = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write)) { Task t = f.WriteAsync(attachment.Data, 0, attachment.Data.Length); t.ContinueWith((prevTask) => { System.Diagnostics.Process.Start(filename); }); } } finally { if (message != null) { message.Dispose(); } } } }catch (IOException ex) { Console.WriteLine("ex", ex.Message); } } else { lblStatus.Text = "Error"; } }
private void button1_Click(object sender, EventArgs e) { //Extract the email folder to a path where you can use it String folderPath = "C:\\Users\\Joe\\Desktop\\DistributionEmails\\Files"; Int32 iCountNum = 0; //Only open files that are email messages foreach (String file in Directory.EnumerateFiles(folderPath, "*.msg")) { try { OutlookStorage.Message outlookMsg = new OutlookStorage.Message(file); //Loop through the messages attachments foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments) { byte[] attachBytes = attach.Data; if (attach.Filename.IndexOf(".pdf") > -1 || attach.Filename.IndexOf(".dwf") > -1) { textBox1.AppendText(iCountNum.ToString() + ". " + file + System.Environment.NewLine); int iPos = file.LastIndexOf("\\") + 1; //The filenames come in a few formats. This is the best we have to information about what's in the email string filename = file.Substring(iPos, (file.Length - iPos)); String[] arrItems = Regex.Split(filename, " - "); //connect to the database String strConn = "Server=mlawdb.cja22lachoyz.us-west-2.rds.amazonaws.com;Database=MLAW_MS;User Id=sa;Password=!sd2the2power!;"; SqlConnection conn = new SqlConnection(strConn); String strMLAWNumber = ""; if (arrItems.Length > 1) { //First item is always the date, strip out the word Transmittal if it's in there String strDate = arrItems[0]; strDate = strDate.Replace("Transmittal", "").Trim(); DateTime dtTime = DateTime.MinValue; try { dtTime = Convert.ToDateTime(strDate); } catch (System.Exception ex) { MessageBox.Show(file + ":::" + strDate); } textBox1.AppendText(dtTime.ToString() + System.Environment.NewLine); for (int i = 1; i < arrItems.Length; i++) { textBox1.AppendText(arrItems[i].ToString() + System.Environment.NewLine); if (!isTransmittal(arrItems[i].ToString())) { String strThis = arrItems[i].ToString().Trim(); strThis = strThis.Replace(".msg", ""); int iCount = strThis.Count(char.IsLetter); if (iCount < 2 && strThis.Length > 7) { iCountNum += 1; strThis = strThis.Replace(" ", "."); strMLAWNumber = strThis; textBox1.AppendText(iCountNum.ToString() + ". " + strThis + System.Environment.NewLine); } } } if (strMLAWNumber == "") { String strAddress = ""; for (int i = 1; i < arrItems.Length; i++) { if (!isTransmittal(arrItems[i].ToString())) { String strThis = arrItems[i].ToString().Trim(); strThis = strThis.Replace(".msg", ""); int iCount = strThis.Count(char.IsLetter); textBox1.AppendText("Address: " + strThis + System.Environment.NewLine); DataSet ds = new DataSet(); //Try to find our MLAW Number based on the Address and the date delivered SqlCommand sqlComm = new SqlCommand("Get_MLAW_Number_By_Delivery", conn); sqlComm.Parameters.AddWithValue("@Address", strThis); sqlComm.Parameters.AddWithValue("@Date", dtTime); sqlComm.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = sqlComm; da.Fill(ds); if (ds.Tables[0].Rows.Count > 0 && strMLAWNumber == "") { strMLAWNumber = ds.Tables[0].Rows[0]["MLAW_Number"].ToString(); } } } //If we manage to get an MLAW Number then we can do something with our file. if (strMLAWNumber != "") { DataSet dsMLAWNum = new DataSet(); SqlCommand sqlCommMLAWNum = new SqlCommand("Get_Order_By_MLAW_Number", conn); sqlCommMLAWNum.Parameters.AddWithValue("@MLAW_Number", strMLAWNumber); sqlCommMLAWNum.CommandType = CommandType.StoredProcedure; SqlDataAdapter daMLAWNum = new SqlDataAdapter(); daMLAWNum.SelectCommand = sqlCommMLAWNum; daMLAWNum.Fill(dsMLAWNum); if (dsMLAWNum.Tables[0].Rows.Count > 0) { SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary); fileP.Value = attachBytes; SqlParameter sqlOrderId = new SqlParameter("@MLAW_Number", SqlDbType.VarChar); sqlOrderId.Value = strMLAWNumber; SqlParameter sqlFileName = new SqlParameter("@File_Name", SqlDbType.VarChar); String strFileInDB = attach.Filename; sqlFileName.Value = strFileInDB; SqlCommand myCommand = new SqlCommand(); myCommand.Parameters.Add(fileP); myCommand.Parameters.Add(sqlOrderId); myCommand.Parameters.Add(sqlFileName); conn.Open(); myCommand.Connection = conn; myCommand.CommandText = "Insert_Order_File_2"; myCommand.CommandType = CommandType.StoredProcedure; myCommand.ExecuteNonQuery(); conn.Close(); } } } } } } if (outlookMsg != null) { outlookMsg.Dispose(); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Drop event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void OnDrop(object sender, Telerik.Windows.DragDrop.DragEventArgs e) { // Find RadTreeViewItem var item = e.OriginalSource as RadTreeViewItem; if (e.OriginalSource != null && e.OriginalSource is DependencyObject) { var dependencySource = (DependencyObject)e.OriginalSource; item = Framework.UI.WPFVisualTreeHelper.FindParent <RadTreeViewItem>(dependencySource); } var targetDirectory = item?.DataContext as DirectoryViewModel; // Save target filestructure before drop action if (targetDirectory.StructureViewModel.IsDirty) { targetDirectory.StructureViewModel.Save(); } //Check if the the folder is a workflow folder and has a workflow assigned if (IsWorkflowDirectory(targetDirectory)) { return; } // File drag & drop DataObject dataObject = (e.Data as DataObject); var refreshDirectoryPath = true; if (dataObject != null && dataObject.ContainsFileDropList()) { foreach (var file in dataObject.GetFileDropList()) { Helper.ArchiveHelper.ArchiveFile(targetDirectory.StructureViewModel.Model, targetDirectory.Model, file); } refreshDirectoryPath = false; } else if (dataObject != null && dataObject.GetData("FileGroupDescriptorW") != null) { var outlookDataObject = new OutlookDataObject(dataObject); string[] filenames = (string[])outlookDataObject.GetData("FileGroupDescriptorW"); var fileStreams = (MemoryStream[])outlookDataObject.GetData("FileContents"); string directory = GlobalSettings.AppDataPath + "\\Temp\\Blobs\\"; if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } for (int fileIndex = 0; fileIndex < filenames.Length; fileIndex++) { //use the fileindex to get the name and data stream string filename = filenames[fileIndex]; MemoryStream filestream = fileStreams[fileIndex]; //save the file stream using its name to the application path FileStream outputStream = File.Create(directory + filename); filestream.WriteTo(outputStream); outputStream.Close(); if (filename.ToLower().EndsWith(".msg")) { try { OutlookStorage.Message msg = new OutlookStorage.Message(directory + filename); DateTime receiveDateTime = msg.ReceivedDate; msg.Dispose(); File.SetLastWriteTime(directory + filename, receiveDateTime); } catch (Exception ex) { Log.LogManagerInstance.Instance.Error(string.Format(@"Invalid mail format: {0}", filename), ex); } } else { File.SetLastWriteTime(directory + filename, DateTime.Now); } Helper.ArchiveHelper.ArchiveFile(targetDirectory.StructureViewModel.Model, targetDirectory.Model, directory + filename); } refreshDirectoryPath = false; } else if (dataObject != null && dataObject.GetData(typeof(GridViewPayload)) != null) { var service = CommonServiceLocator.ServiceLocator.Current.GetInstance <IFileStructureDocumentPathService>(); var localizationService = CommonServiceLocator.ServiceLocator.Current.GetInstance <ILocalizationService>(); var payload = dataObject.GetData(typeof(GridViewPayload)) as GridViewPayload; foreach (var path in payload.DataObjects.OfType <FileStructureDocumenPath>()) { var copyMode = Keyboard.Modifiers == ModifierKeys.Shift; if (copyMode) { var newPath = new FileStructureDocumenPath { DirectoryGuid = targetDirectory.Model.Id, FileStructureGuid = targetDirectory.StructureViewModel.Model.Id, DocumentGuid = path.DocumentGuid, WorkflowId = targetDirectory.Model.WorkflowId }; service.Save(newPath); } else { if (path.IsProtectedPath) { MessageBox.Show(localizationService.Translate("filestructure_path_protected"), localizationService.Translate("filestructure_path_protected_title"), MessageBoxButton.OK, MessageBoxImage.Information); continue; } path.DirectoryGuid = targetDirectory.Model.Id; path.WorkflowId = targetDirectory.Model.WorkflowId; path.FileStructureGuid = targetDirectory.StructureViewModel.Model.Id; service.Save(path); } if (targetDirectory.Model.WorkflowId != null) { var configurationService = CommonServiceLocator.ServiceLocator.Current.GetInstance <Workflow.IDocumentWorkflowConfigurationService>(); var workflow = configurationService.Get(targetDirectory.Model.WorkflowId.Value); if (!string.IsNullOrWhiteSpace(workflow.AccessProviderName)) { var accessProvider = CommonServiceLocator.ServiceLocator.Current.GetInstance <Workflow.IDocumentWorkflowAccessProvider>(workflow.AccessProviderName); accessProvider.SetUserAccess(GlobalSettings.UserId, path.DocumentGuid, path.Id, path.FileStructureGuid, workflow); } } } refreshDirectoryPath = false; // Refresh grid if (payload.Grid is CursorGridViewControl) { (payload.Grid as CursorGridViewControl).RefreshData(); } } // Save target filestructure before drop action if (refreshDirectoryPath) { targetDirectory.StructureViewModel.Save(); var directoriesToCheck = new List <DirectoryViewModel>(); directoriesToCheck.Add(targetDirectory); //Recalculating the path through the save method while (directoriesToCheck.Any()) { var innerDirectories = new List <DirectoryViewModel>(); foreach (var subDirectory in directoriesToCheck) { var guid = subDirectory.Model.Id; var list = fileStructureDocumentPathService.GetByDirectoryId(guid); foreach (FileStructureDocumenPath fileStructureDocumenPath in list) { fileStructureDocumentPathService.Save(fileStructureDocumenPath); } innerDirectories.AddRange(subDirectory.Directories); } directoriesToCheck.Clear(); directoriesToCheck.AddRange(innerDirectories); } } }
// Each message is opened and a tabpage is created dynamically with a header and body box private void load_files(string msgfile, string holder, ref int TabCount, string ruleTxt = "", bool fromNode = false) { bool rulesFileHere = check_for_rules(); myTab = new TabPage(holder); myTab.Text = holder; TextBox HeaderBox = new TextBox(); HeaderBox.Multiline = true; HeaderBox.Width = 550; HeaderBox.Height = 960; HeaderBox.Location = new Point(650, 0); HeaderBox.ScrollBars = ScrollBars.Both; HeaderBox.ReadOnly = true; HeaderBox.BackColor = Color.White; HeaderBox.WordWrap = false; headerSizeDec.Enabled = true; headerSizeInc.Enabled = true; HeaderBox.ContextMenuStrip = headerMenu; myTab.Controls.Add(HeaderBox); TextBox BodyBox = new TextBox(); BodyBox.Multiline = true; BodyBox.Width = 650; BodyBox.Height = 960; BodyBox.ScrollBars = ScrollBars.Both; BodyBox.ReadOnly = true; BodyBox.BackColor = Color.White; BodyBox.WordWrap = false; bodySizeDec.Enabled = true; bodySizeInc.Enabled = true; BodyBox.ContextMenuStrip = bodyMenu; myTab.Controls.Add(BodyBox); Regex regex_txt = new Regex(@"\.txt$"); Regex regex_msg = new Regex(@"\.msg$"); Regex regex_eml = new Regex(@"\.eml$"); Match match_txt = regex_txt.Match(msgfile); Match match_msg = regex_msg.Match(msgfile); Match match_eml = regex_eml.Match(msgfile); TabCount = TabCount + 1; // What type of file are we trying to open. if (match_msg.Success) { Stream messageStream; try { messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "File Error", MessageBoxButtons.OK); return; } OutlookStorage.Message message = new OutlookStorage.Message(messageStream); messageStream.Close(); HeaderBox.Text = message.GetMapiPropertyString("007D"); BodyBox.Text = message.BodyText; message.Dispose(); } else if (match_eml.Success || match_txt.Success) { StreamReader mStream; try { mStream = new StreamReader(msgfile); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "File Error", MessageBoxButtons.OK); return; } bool reachedBody = false; bool firstLine = true; string header = ""; string body = ""; while (mStream.Peek() >= 0) { string lineTest = mStream.ReadLine(); if (lineTest != "" && reachedBody == false) { if (!firstLine) { header = header + "\r\n" + lineTest; } else { header = lineTest; firstLine = false; } reachedBody = false; } else if (lineTest == "" && reachedBody == false) { reachedBody = true; firstLine = true; HeaderBox.Text = header; } if (reachedBody) { if (!firstLine) { body = body + "\r\n" + lineTest; } else { body = lineTest; firstLine = false; } } } BodyBox.Text = body; } // Add a new node to the tree view for these files messageNodeInfo nodeNew = new messageNodeInfo(); nodeNew.headerText = HeaderBox.Text; nodeNew.bodyText = BodyBox.Text; nodeNew.tNode.Text = holder; nodeNew.tNode.Name = msgfile; nodeNew.filePath = msgfile; nodeNew.fileName = holder; nodeNew.tNode.ContextMenuStrip = contextMenuStrip2; nodeList.Add(nodeNew); tabControl1.TabPages.Add(myTab); //tabControl1.Hide(); closeBtn.Enabled = true; button1.Enabled = true; closeAllBtn.Enabled = true; // If a top level treeview node is already selected add the new files to that node // Otherwise create a new toplevel node if (treeView1.SelectedNode != null) { if (treeView1.SelectedNode.Level != 0 && fromNode == false) { treeView1.SelectedNode.Parent.Nodes.Add(nodeNew.tNode); nodeNew.pNodeIndex = treeView1.SelectedNode.Parent.Index; } else if (fromNode == false) { treeView1.SelectedNode.Nodes.Add(nodeNew.tNode); nodeNew.pNodeIndex = treeView1.SelectedNode.Index; } treeView1.SelectedNode.Expand(); } else if (treeView1.SelectedNode == null) { if (treeView1.Nodes.ContainsKey("Untitled") == false) { TreeNode newTopNode = new TreeNode("Untitled"); newTopNode.Name = "Untitled"; newTopNode.ContextMenuStrip = contextMenuStrip1; nodeNew.pNodeIndex = treeView1.Nodes.Count; newTopNode.Nodes.Add(nodeNew.tNode); treeView1.Nodes.Add(newTopNode); treeView1.SelectedNode = treeView1.Nodes[newTopNode.Name]; } else { ; } } else { ; } }