// Lưu những thay đổi trước khi đóng hoặc hủy không đóng nữa private void frmRead_FormClosing(object sender, FormClosingEventArgs e) { FileM file = FileController.getFileM(fileCode); file.iRead = maxPage; file.dtRecentlyRead = DateTime.Now; if (file.sNote != rtbNote.Text.Trim() && rtbNote.Text.Length > 0 || checkDraw == true) { DialogResult dr = MessageBox.Show("Bạn có muốn lưu các thay đổi cho " + file.sTitle + "?", "Thông báo", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (dr == DialogResult.Yes) { file.sNote = rtbNote.Text.Trim(); if (checkDraw == true) { using (FileStream fileStream = new FileStream(String.Format("{0}.jpg", fileCode), FileMode.Create)) { ptbNote.Image.Save(fileStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } else if (dr == DialogResult.Cancel) { e.Cancel = true; // Không đóng form } } FileController.updateFile(file); // cập nhật xuống dtb exit = true; }
// Lưu thứ tự đọc File private void btnSaveReadIndex_Click(object sender, EventArgs e) { List <FileM> lF = new List <FileM>(); lF = FileController.getListFile(); foreach (var f in lF) { if (f.sTitle == this.cbCurrentFile.SelectedItem.ToString()) // Nếu tên file trong danh sách file bằng với file hiện tại người dùng chọn { FileM file = new FileM(); // Khởi tạo object file của lớp FileM và gán các giá trị của file hiện tại người dùng chọn vào object file file.iFileCode = f.iFileCode; file.iRead = f.iRead; file.sCategory = f.sCategory; file.sFilePreview = this.rtbShowFileReadPreview.Text; // Gán file cần đọc trước do người dùng chọn vào sFilePreview file.sLinkFile = f.sLinkFile; file.sLinkPic = f.sLinkPic; file.sTitle = f.sTitle; file.sNote = f.sNote; file.dtDateUpdate = f.dtDateUpdate; file.dtRecentlyRead = f.dtRecentlyRead; FileController.updateFile(file); // Xử lý yêu cầu cập nhật lại file trong database MessageBox.Show("Lưu thành công!"); // Thông báo cho người dùng. // Gán về giá trị ban đầu là "" this.cbCurrentFile.Text = ""; this.rtbShowFileReadPreview.Text = ""; this.cbReadPreview.Enabled = false; } } }
public frmRead(ref List <FileM> fileM, int filecode, bool darkmode) { InitializeComponent(); drawNote = new DrawNote(); FileM file = FileController.getFileM(filecode); fileCode = filecode; linkFile = file.sLinkFile; if (file.iRead == 0) { file.iRead += 1; FileController.updateFile(file); } currentPage = file.iRead; maxPage = file.iRead; if (file.sNote != null) { rtbNote.Text = file.sNote; btnDeleteNote.Enabled = true; // nếu tồn tại ghi chú thì bật nút xóa } cbbWidth.Text = cbbWidth.GetItemText(cbbWidth.Items[0]).ToString(); // Xử lý chế độ sáng tối if (darkmode == true) { DarkMode = darkmode; darkMode(); } else { DarkMode = darkmode; lightMode(); } }
// Hiển thị file đọc gần nhất private void lastRead(string filecode) { lbFileCode.Text = filecode; if (filecode != "") { btnReadLastFile.Enabled = true; FileM file = FileController.getFileM(int.Parse(lbFileCode.Text.ToString())); if (file is null) { this.lbTitle.Text = ""; picLastFile.Image.Dispose(); return; } lbTitle.Text = file.sTitle; using (FileStream stream = new FileStream(String.Format(file.sLinkPic), FileMode.Open, FileAccess.Read)) { picLastFile.Image = Image.FromStream(stream); } G = Graphics.FromImage(picLastFile.Image); } else { btnReadLastFile.Enabled = false; } }
// Lưu file private void btnSave_Click(object sender, EventArgs e) { checkError(); if (error == false) { FileM file = new FileM(); // Khởi tạo object file của lớp FileM file.iFileCode = FileController.getFileCodeFromDB(); // Sinh mã số file tự động file.sTitle = this.txtTitle.Text.Trim(); // Gán tên file do người dùng tải lên có sẵn hoặc đổi tên khác file.sCategory = category; // Gán các thể loại mà người dùng đã chọn file.dtDateUpdate = DateTime.Now; // Thời gian người dùng thêm file vào file.iRead = 0; // Gán số trang mà người dùng đã đọc (hiện tại mới thêm vào thì là 0) file.dtRecentlyRead = null; // Gán thời gian đọc file gần nhất (hiện tại mới thêm vào nên là null) if (clickPicUpload == true) // Nếu người dùng có tải bìa file { file.sLinkPic = openIMG.FileName; // Gán đường dẫn của ảnh bìa } else { file.sLinkPic = pathOriginalIMG; // Nếu người dùng không tải bìa thì sử dụng bìa mặc định } file.sLinkFile = openFile.FileName; // Gán đường dẫn file save = true; if (FileController.addFile(file) == false) // Xử lý yêu cầu thêm file truyền xuống database (true là thành công, false là thất bại) { error = true; save = false; } } this.Close(); }
public async Task <ActionResult> UploadFileAsync( [FromServices] IFileRepository fileContext, [FromServices] IUserRepository userContext, [FromServices] DataContext dataContext, [FromServices] IWebHostEnvironment environment ) { var username = this.User.Identity.Name; var user = await userContext.findByUsername(username); if (user == null) { return(BadRequest("user not found")); } var files = HttpContext.Request.Form.Files; if (files.Count != 1) { return(BadRequest("problem 01")); } var ImagePath = environment.WebRootPath + "\\Upload\\"; var Extension = Path.GetExtension(files[0].FileName); var fileName = user.username + "-" + user.id + Extension; var RelativeImagePath = ImagePath + fileName; try{ var hasFile = fileContext.findFileByUserId(user.id); if (hasFile != null) { fileContext.deleteFile(hasFile); System.IO.File.Delete(hasFile.path); } using (FileStream fileStream = System.IO.File.Create(RelativeImagePath)) { files[0].CopyTo(fileStream); fileStream.Flush(); var file = new FileM() { filename = fileName, path = RelativeImagePath, UserId = user.id, link = "https://localhost:5001/upload/" + fileName }; user.Image = file; fileContext.addFile(file); await dataContext.SaveChangesAsync(); return(Ok(fileName)); } }catch (Exception ex) { Console.WriteLine("PROBLEM FINAL ERROR"); return(BadRequest(ex.Message)); } }
private static FileM Convert(FileInfo fileInfo) { var fileM = new FileM() { Name = fileInfo.Name, Size = fileInfo.Length }; return(fileM); }
// Xóa file public static bool deleteFile(FileM file) { using (var _context = new DBFileContext()) { var dbfile = (from f in _context.tbFileMs where f.iFileCode == file.iFileCode select f).SingleOrDefault(); _context.tbFileMs.Remove(dbfile); _context.SaveChanges(); return(true); } }
// Đọc file gần nhất bằng Double Click private void pnlLastRead_MouseDoubleClick(object sender, MouseEventArgs e) { if (lbFileCode.Text != "") { FileM file = FileController.getFileM(int.Parse(lbFileCode.Text.ToString())); frmRead read = new frmRead(ref fileM, file.iFileCode, darkmode); read.Text = this.dataFileM.CurrentRow.Cells[1].Value.ToString(); read.ShowDialog(); if (read.exit == true) { loadData(); } } }
// Thêm File public static bool addFile(FileM file) { try { using (var _context = new DBFileContext()) { _context.tbFileMs.Add(file); _context.SaveChanges(); return(true); } } catch { return(false); } }
// Xóa File private void toolDelete_Click(object sender, EventArgs e) { if (MessageBox.Show("Bạn chắc chắn xóa file này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { FileM file = FileController.getFileM(int.Parse(this.FileCode)); FileController.deleteFile(file); try // nếu đã tồn tại hình vẽ thì xóa (nghĩa là hình vẽ đã được lưu) { File.Delete(String.Format("{0}.jpg", int.Parse(this.FileCode))); } catch { // không có hình vẽ thì thôi } MessageBox.Show("Nhấn Ctrl+R để làm mới chương trình!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
// Đọc file gần nhất bằng Button private void btnReadLastFile_Click(object sender, EventArgs e) { if (lbFileCode.Text != "") { FileM file = FileController.getFileM(int.Parse(lbFileCode.Text.ToString())); if (file is null) { return; } frmRead read = new frmRead(ref fileM, file.iFileCode, darkmode); read.Text = file.sTitle; read.ShowDialog(); if (read.exit == true) { loadData(); } } }
// Hiển thị dạng lưới private void showThumb() { if (flpnlThumb.Controls.Count > 0) { flpnlThumb.Controls.Clear(); // Xóa các control trên flowlayoutpanel để không bị hiện lặp lại } for (int i = 0; i < dataFileM.RowCount; i++) { usrViewThumb listView1 = new usrViewThumb(darkmode); FileM file = FileController.getFileM(int.Parse(this.dataFileM.Rows[i].Cells[0].Value.ToString())); listView1.Title = file.sTitle; listView1.Category = file.sCategory; listView1.FileCode = file.iFileCode.ToString(); listView1.RecentlyRead = file.dtRecentlyRead.ToString(); listView1.Note = file.sNote; listView1.LinkFile = file.sLinkFile; listView1.DarkMode = darkmode; try { using (FileStream stream = new FileStream(String.Format(file.sLinkPic), FileMode.Open, FileAccess.Read)) { listView1.PictureFile.Image = Image.FromStream(stream); } } catch { // Trường hợp đường dẫn hình ảnh không còn tồn tại listView1.PictureFile.Image = Image.FromFile("..//..//Pictures//ErrorIMG.jpeg"); } G = Graphics.FromImage(listView1.PictureFile.Image); flpnlThumb.Controls.Add(listView1); //Mới thêm vào + chưa đọc thì hiện icon New if (file.dtDateUpdate.ToString("dd/MM/yyyy") == DateTime.Now.ToString("dd/MM/yyyy") && file.iRead == 0) { listView1.PictureNewIcon.Visible = true; } else { listView1.PictureNewIcon.Visible = false; } } }
// Lưu ghi chú private void btnSave_Click(object sender, EventArgs e) { FileM file = FileController.getFileM(fileCode); if (rtbNote.Text.Length > 0) // có ghi chú mới lưu { file.sNote = rtbNote.Text.Trim(); } if (checkDraw == true) // vẽ thì lưu { using (FileStream fileStream = new FileStream(String.Format("{0}.jpg", fileCode), FileMode.Create)) { ptbNote.Image.Save(fileStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } checkDraw = false; FileController.updateFile(file); // cập nhật xuống dtb MessageBox.Show("Lưu thành công!", "Thông báo", MessageBoxButtons.OK); }
// Cập nhật toàn bộ frmManager public void loadData() { source.DataSource = FileController.getListFile(); dataFileM.DataSource = source; if (FileController.getListFile().Count <= 1) { addReadIndex.Enabled = false; } else { addReadIndex.Enabled = true; } // Kiểm tra LastRead dtLast = DateTime.MinValue; for (int i = 0; i < FileController.getListFile().Count; i++) { FileM file = FileController.getFileM(int.Parse(this.dataFileM.Rows[i].Cells[0].Value.ToString())); try { if (DateTime.Compare(file.dtRecentlyRead.Value, dtLast) > 0) // Gần nhất { dtLast = file.dtRecentlyRead.Value; lbFileCode.Text = file.iFileCode.ToString(); } } catch { } } if (lbFileCode.Text != "") { lastRead(lbFileCode.Text.ToString().Trim()); // Khởi tạo nếu có file đọc gần nhất } else { picLastFile.Dispose(); lbTitle.Text = ""; lbFileCode.Text = ""; } showThumb(); this.UpdateCategory(); }
// Dạng danh sách: Xóa File private void dataFileM_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (this.dataFileM.Columns[e.ColumnIndex].Name == "cDelete") { if (MessageBox.Show("Bạn chắc chắn xóa file này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { FileM file = FileController.getFileM(int.Parse(this.dataFileM.Rows[e.RowIndex].Cells[0].Value.ToString())); FileController.deleteFile(file); try // nếu đã tồn tại hình vẽ thì xóa (nghĩa là hình vẽ đã được lưu) { File.Delete(String.Format("{0}.jpg", int.Parse(this.dataFileM.Rows[e.RowIndex].Cells[0].Value.ToString()))); } catch { // không có hình vẽ thì thôi } } loadData(); } }
public frmProperties(ref List <FileM> fileM, int filecode, bool darkmode) { InitializeComponent(); FileM file = FileController.getFileM(filecode); fileCode = filecode; linkFile = file.sLinkFile; this.lbTitle.Text = file.sTitle; this.lbFileCode.Text = file.iFileCode.ToString(); this.lbCategory.Text = file.sCategory; this.lbDateAdd.Text = file.dtDateUpdate.ToString(); this.lbRecentlyRead.Text = file.dtRecentlyRead.ToString(); this.lbLinkFile.Text = file.sLinkFile; if (file.sFilePreview == null) { this.lbReadPreview.Text = ""; } else { this.lbReadPreview.Text = file.sFilePreview.ToString(); } using (FileStream stream = new FileStream(String.Format(file.sLinkPic), FileMode.Open, FileAccess.Read)) { picFile.Image = Image.FromStream(stream); } // Xử lý chế độ sáng tối if (darkmode == true) { DarkMode = darkmode; darkMode(); } else { DarkMode = darkmode; lightMode(); } }
static void Main(string[] args) { repiat: Console.Clear(); Console.WriteLine("НАчинаю работу приложения"); /************************переменные для логера**************************/ const string Error_ = "Ошибка"; const string Warning_ = "Предупреждение"; const string Event_ = "Событие"; /************************переменные для логера конец********************/ //Logger.Run_(); Logger.WriteLog(Event_, 0, "Старт"); /**********Выполняем батники для отправки**********/ /***********Переменные для батников*********/ string batPuttyOut1 = @"C:\tkM\copyOUTputty.bat"; string batPuttyOut2 = @"C:\tkM\copyOUTarch.bat"; string batInPutty1 = @"C:\tkM\copyOUTarch.bat"; string batInPutty2 = @"C:\tkM\copyOUTarch.bat"; string pathBat = @"C:\tkM"; string descrBatO1 = "fromPuttyToOut1"; string descrBatO2 = "fromPuttyToOut2"; string descrBatI3 = "fromPuttyToIN1"; string descrBatI4 = "fromPuttyToIN2"; //*************батники на отправку*********// FileM.ProcManage(batPuttyOut1, pathBat, descrBatO1); FileM.ProcManage(batPuttyOut2, pathBat, descrBatO2); //try //{ //System.Diagnostics.Process proc = new System.Diagnostics.Process(); //proc.StartInfo.FileName = @"C:\tkM\copyOUTarch.bat"; //proc.StartInfo.WorkingDirectory = @"C:\tkM"; //proc.Start(); //proc.WaitForExit(); // Console.WriteLine("Батники на отправку успешно отработали"); // Logger.WriteLog(Event_ , 0, "Батники на отправку успешно отработали"); // proc = null; //ufc //} //catch(System.Exception ex) //{ // Logger.WriteLog(Error_, 100 , "ошибка выолнения батников" + Convert.ToString(ex.Message)); // Console.WriteLine("ошибка выолнения батников" + Convert.ToString(ex.Message)); //} /********************/ Logger.WriteLog(Event_, 0, "Выполняю модуль отправки писем"); Console.WriteLine("Выполняю модуль отправки писем"); //Outlook.Application application; // Outlook._NameSpace nameSpace; Outlook.MAPIFolder folderInbox; ////////////////////////////////// //Microsoft.Office.Interop.Outlook._Folders oFolders; ///////////////1 модуль отправки файлов/////////////////// string[] dirs; dirs = Directory.GetFiles(@"C:\tkM\OUT"); //дирректория - откуда берём файл String dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо for (int i = 0; i < dirs.Length; i++) //для отправки 1 письмо + 1 файл { Logger.WriteLog(Event_, 0, "Запускаю цикл обработки и отправки входящих файлов"); if (Convert.ToInt32(dirs1count) > 0) { Logger.WriteLog(Event_, 0, "Колличество файлов на отправку: " + dirs1count); Console.WriteLine("Выполняю модуль отправки писем"); //string dirArch = "C://OUT//ARCH//"; try { //тело отправляемого сообщения Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); mail.To = "*****@*****.**"; //"*****@*****.**"; mail.Subject = "test1567"; // тема mail.Body = "This is test message1156711"; //текст письма mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь foreach (string s in dirs) { try { Console.WriteLine(s); mail.Attachments.Add(s); //добавляем вложения в письмо - возможно добавить сразу все вложения File.Move(s, s.Replace("OUT", "ARCH")); //После успешного прикрепления файла, переносим их в папку C:\ARCH ((Outlook._MailItem)mail).Send(); //отправляем письмо Console.WriteLine("Файл" + s + "отправлен в ТК"); // если все хорошо, то выдаём в консоль сообщение Logger.WriteLog(Event_, 0, "Файл" + s + "отправлен в ТК"); break; // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом } catch (System.Exception ex) { Logger.WriteLog(Warning_, 201, "Системное исключение" + ex.Message); Logger.WriteLog(Warning_, 200, "С таким именем файла уже отправлялось\n" + "Перемещаю файл" + s + "в папку Bad также прочти системное исключение"); Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad"); FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных System.Threading.Thread.Sleep(1000); //спим 1000 мс что б увидеть работу кода } } Logger.WriteLog(Event_, 0, "успешно передан файл" + dirs[i]); _app = null; //убиваем ссылки на экземпляр класса mail = null; //Console.Read(); } catch (System.Exception ex) { Logger.WriteLog(Error_, 111, "Системная информация" + ex.Message); Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов"); System.Threading.Thread.Sleep(1000); Logger.WriteLog(Warning_, 300, "Переходим к модулю обработки входящих писем"); goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений } ////////////////////////////Чтение сообщений и копирование вложений/////////////////////////////////////////// } else { Console.WriteLine("Файлов для отправки нет"); Logger.WriteLog(Event_, 0, "Файлов для отправки нет - Переходим к модулю обраюлтки входящих писем"); break; } //если нет файлов во вложении то выходим из цикла dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); dirs = Directory.GetFiles(@"C:\tkM\OUT"); //переинициализируем переменную с каждым шагом цикла - так как файлов то меньше на 1 System.Threading.Thread.Sleep(1000); } importStart: Logger.WriteLog(Event_, 0, "Обрабатываем входящие письма"); Outlook.Application oApp = new Outlook.Application();// создали новый экземпляр Outlook.NameSpace oNS = oApp.GetNamespace("MAPI"); //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие) //oNS.Logon(Missing.Value, Missing.Value, false, true); //Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //for (int x = 1; x <= oInbox.Items.Count; x++) //{ // if (oInbox.Items[x] is MailItem) // { // //Выводим Имя отправителя // Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n"); // } //} nameSpace = oApp.GetNamespace("MAPI"); object missingValue = System.Reflection.Missing.Value; folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Outlook.OlDefaultFolders.olFolderInbox //количество не прочитанных писем в папке Входящие (Inbox) Outlook.MAPIFolder rootFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие Outlook.MAPIFolder processedFolder = null; //processedFolder это экземпляр класса который выбирает нужную папку foreach (Outlook.MAPIFolder folder in rootFolder.Folders) // ищем циклом папку в OUTLOOK { if (folder.Name == "IN") //берем из папки IN { processedFolder = folder; // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK) break; } } Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true"); // работаем с данной папкой и ищем не прочитанные письма Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений Logger.WriteLog(Event_, 0, "Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); //////////здесь вываодим в консоль все данные непрочитанные письма в папке in можно заккоментить///////////////////////// StringBuilder str = new StringBuilder(); //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования try { DateTime sysdate_ = DateTime.Now; foreach (Outlook.MailItem mailItem in unreadItems) { Logger.WriteLog(Event_, 0, "Читаю письмо"); str.AppendLine("----------------------------------------------------"); str.AppendLine("SenderName: " + mailItem.SenderName); str.AppendLine("To: " + mailItem.To); str.AppendLine("CC: " + mailItem.CC); str.AppendLine("Subject: " + mailItem.Subject); str.AppendLine("Body: " + mailItem.Body); str.AppendLine("CreationTime: " + mailItem.CreationTime); str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName); str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime); str.AppendLine("UnRead: " + mailItem.UnRead); str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString()); str.AppendLine("----------------------------------------------------"); Console.WriteLine(str.ToString()); Logger.WriteLog(Event_, 0, str.ToString()); } } catch (System.Exception ex) // если письмо бракованное то пробуем ещё раз { //System.Threading.Thread.Sleep(300); //пауза //goto repeatReadMail; Logger.WriteLog(Error_, 102, "Ощибка сохранения письма или" + ex.Message); string errorInfo = (string)ex.Message.Substring(0, 11); Console.WriteLine(errorInfo);// вывести любую ошибку if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\TestFileSave"); } Logger.WriteLog(Event_, 0, "Перехожу к чтению вложений"); goto repeatReadAndAddAttachmentIsMail; // перейти к чтению и вытаскиванию вложения в случае ошибки здесь } //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять //{ // if (mail.UnRead) // { // mail.UnRead = false; // mail.Save(); // } //} //////////////////Вытаскивание вложение и пометить письмо как прочитанное repeatReadAndAddAttachmentIsMail: Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true");//show unread message and inicialise varible Outlook.MailItem newEmail = null; try { foreach (object collectionItem in inBoxItems) { newEmail = collectionItem as Outlook.MailItem; DateTime sysdate_ = DateTime.Now; //SYSDATE //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString(); if (newEmail != null /*&& newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()*/) //checj date of mail { if (newEmail.Attachments.Count > 0) { for (int i = 1; i <= newEmail.Attachments.Count; i++) { string fileName = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName); string[] dirsaRCH = Directory.GetFiles(@"C:\tkM\ARCH\");//создадим перепенную с именами файлов в папке ARCH что бы проверять файлы в архиве if (FileM.ValueOf(dirsaRCH, fileName) != "noDuble") { Console.WriteLine(@"Найдено совпаление с файлом: " + fileName + "\n Список файлов в папке:"); Logger.WriteLog(Warning_, 0, @"Найдено совпаление с файлом: " + fileName + "не обратываем"); //for (int i1 = 0; i1 < dirsaRCH.Length; i1++) //{ // Console.Write( dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n"); // Logger.WriteLog(Warning_, 205, dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n"); //} } else { Console.WriteLine(@"нет совпадения файлов"); Logger.WriteLog(Event_, 0, @"Совпадений по имени не найдено"); //Console.WriteLine(@"Имя файла:" + fileName); //for (int i1 = 0; i1 < dirsaRCH.Length; i1++) //{ // Console.Write("Имя файлов(а) в папке:" + dirsaRCH[i1]); //} newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName); Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла Logger.WriteLog(Event_, 0, @"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); } // { Console.WriteLine(@"Обрабатываю письмо как прочитанное"); Logger.WriteLog(Event_, 0, @"Обрабатываю письмо как прочитанное"); System.Threading.Thread.Sleep(1000); if (newEmail.UnRead) // пометить письмо как прочитанное { newEmail.UnRead = false; newEmail.Save(); } /********батники на IN************/ FileM.ProcManage(batInPutty1, pathBat, descrBatI3); FileM.ProcManage(batInPutty2, pathBat, descrBatI4); /********************/ string[] dirIN = Directory.GetFiles(@"C:\tkM\IN"); foreach (string d in dirIN) { FileM.MoveReplaceFile(d, d.Replace("IN", "ARCH")); } Console.WriteLine(@"Завершаю работу"); //} } } } else { Console.WriteLine("Нет писем с вложением"); } } } catch (System.Exception ex) { string errorInfo = (string)ex.Message .Substring(0, 11); Console.WriteLine(errorInfo); if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\IN"); } } //////////выход из приложения oNS.Logoff(); //oInbox = null; oNS = null; oApp = null; //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы Logger.Flush(); Console.WriteLine($"Закончили обработку в {DateTime.Now} " + $"\nСледующий запуск приложения в {DateTime.Now.Add(TimeSpan.FromMinutes(5))} "); System.Threading.Thread.Sleep(15000); goto repiat; }
static void Main(string[] args) { //Outlook.Application application; // Outlook._NameSpace nameSpace; Outlook.MAPIFolder folderInbox; ////////////////////////////////// //Microsoft.Office.Interop.Outlook._Folders oFolders; ///////////////1 модуль отправки файлов/////////////////// string[] dirs; dirs = Directory.GetFiles(@"C:\tkM\OUT"); //дирректория - откуда берём файл String dirs1 = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо for (int i = 0; i <= dirs.Length + 1; i++) //для отправки 1 письмо + 1 файл { if (Convert.ToInt32(dirs1) > 0) { //string dirArch = "C://OUT//ARCH//"; try { //тело отправляемого сообщения Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); mail.To = "*****@*****.**"; //"*****@*****.**"; mail.Subject = "test1567"; // тема mail.Body = "This is test message1156711"; //текст письма mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь foreach (string s in dirs) { try { Console.WriteLine(s); mail.Attachments.Add(s); //добавляем вложения в письмо - возможно добавить сразу все вложения File.Move(s, s.Replace("OUT", "OUTaRCH")); //После успешного прикрепления файла, переносим их в папку C:\ARCH ((Outlook._MailItem)mail).Send(); //отправляем письмо Console.WriteLine("Файл отправлен в ТК"); // если все хорошо, то выдаём в консоль сообщение break; // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом } catch (System.Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad"); FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных System.Threading.Thread.Sleep(1000); //спим 1000 мс что б увидеть работу кода Console.ReadKey(); } } _app = null; //убиваем ссылки на экземпляр класса mail = null; //Console.Read(); } catch { Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов нажми любую клавишу"); System.Threading.Thread.Sleep(1000); goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений } ////////////////////////////Чтение сообщений и копирование вложений/////////////////////////////////////////// } else { Console.WriteLine("Файлов для отправки нет"); break; } //если нет файлов во вложении то выходим из цикла Console.ReadKey(); dirs = Directory.GetFiles(@"C:\tkM\OUT"); //присваивание переменной с каждой итерацией цикла для обновления данных в массиве System.Threading.Thread.Sleep(1000); } importStart: Outlook.Application oApp = new Outlook.Application(); // создали новый экземпляр Outlook.NameSpace oNS = oApp.GetNamespace("MAPI"); //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие) oNS.Logon(Missing.Value, Missing.Value, false, true); Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); for (int x = 1; x <= oInbox.Items.Count; x++) { if (oInbox.Items[x] is MailItem) { //Выводим Имя отправителя Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n"); } } nameSpace = oApp.GetNamespace("MAPI"); object missingValue = System.Reflection.Missing.Value; folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Outlook.OlDefaultFolders.olFolderInbox //количество не прочитанных писем в папке Входящие (Inbox) Outlook.MAPIFolder rootFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие Outlook.MAPIFolder processedFolder = null; //processedFolder это экземпляр класса который выбирает нужную папку foreach (Outlook.MAPIFolder folder in rootFolder.Folders) // ищем циклом папку в OUTLOOK { if (folder.Name == "IN") //берем из папки IN { processedFolder = folder; // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK) break; } } Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true"); // работаем с данной папкой и ищем не прочитанные письма Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений //////////здесь вываодим в консоль все данные непрочитанные письма в папке in можно заккоментить///////////////////////// StringBuilder str = new StringBuilder(); //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования try { DateTime sysdate_ = DateTime.Now; foreach (Outlook.MailItem mailItem in unreadItems) { str.AppendLine("----------------------------------------------------"); str.AppendLine("SenderName: " + mailItem.SenderName); str.AppendLine("To: " + mailItem.To); str.AppendLine("CC: " + mailItem.CC); str.AppendLine("Subject: " + mailItem.Subject); str.AppendLine("Body: " + mailItem.Body); str.AppendLine("CreationTime: " + mailItem.CreationTime); str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName); str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime); str.AppendLine("UnRead: " + mailItem.UnRead); str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString()); str.AppendLine("----------------------------------------------------"); Console.WriteLine(str.ToString()); } } catch (System.Exception ex) // если письмо бракованное то пробуем ещё раз { //System.Threading.Thread.Sleep(300); //пауза //goto repeatReadMail; string errorInfo = (string)ex.Message.Substring(0, 11); Console.WriteLine(errorInfo); // вывести любую ошибку if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\TestFileSave"); } goto repeatReadAndAddAttachmentIsMail; // перейти к чтению и вытаскиванию вложения в случае ошибки здесь } //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять //{ // if (mail.UnRead) // { // mail.UnRead = false; // mail.Save(); // } //} //////////////////Вытаскивание вложение и пометить письмо как прочитанное repeatReadAndAddAttachmentIsMail: Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true"); Outlook.MailItem newEmail = null; try { foreach (object collectionItem in inBoxItems) { newEmail = collectionItem as Outlook.MailItem; DateTime sysdate_ = DateTime.Now; //дата текущий день //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString(); if (newEmail != null && newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()) //проарка на дату файла { if (newEmail.Attachments.Count > 0) { for (int i = 1; i <= newEmail.Attachments.Count; i++) { string fileName = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName); string[] dirsINaRCH = Directory.GetFiles(@"C:\tkM\INaRCH\");//создадим перепенную с именами файлов в папке IN или IN_ARCH if (FileM.ValueOf(dirsINaRCH, fileName) != "noDuble") { Console.WriteLine(@"Найдено совпаление с файлом: " + fileName + "\n Список файлов в папке:"); for (int i1 = 0; i1 < dirsINaRCH.Length; i1++) { Console.Write(dirsINaRCH[i1] + " " + File.GetCreationTime(dirsINaRCH[i1]) + ";\n"); } } else { Console.WriteLine(@"нет совпадения файлов"); //Console.WriteLine(@"Имя файла:" + fileName); //for (int i1 = 0; i1 < dirsINaRCH.Length; i1++) //{ // Console.Write("Имя файлов(а) в папке:" + dirsINaRCH[i1]); //} newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName); Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла } // { Console.WriteLine(@"Обрабатываю письмо как прочитанное"); System.Threading.Thread.Sleep(1000); if (newEmail.UnRead) // пометить письмо как прочитанное { newEmail.UnRead = false; newEmail.Save(); } Console.WriteLine(@"Завершаю работу"); //} } } } else { Console.WriteLine("Нет писем с вложением"); } } } catch (System.Exception ex) { string errorInfo = (string)ex.Message .Substring(0, 11); Console.WriteLine(errorInfo); if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\IN"); } } //////////выход из приложения oNS.Logoff(); oInbox = null; oNS = null; oApp = null; //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы System.Threading.Thread.Sleep(1000); }
public void deleteFile(FileM file) { this._dataContext.Files.Remove(file); }
private void button1_Click(object sender, EventArgs e) { if (Verify.isValidStr(textBox1.Text) && Directory.Exists(textBox1.Text)) { FileM indexFile = new FileM("__index__", "htm", textBox1.Text, true); FileM outlineFile = new FileM("__outline__", "htm", textBox1.Text, true); FileM indexForShowFile = new FileM("index", "htm", textBox1.Text, true); // Prompt before overide if (File.Exists(indexForShowFile.PathNFile)) { MessageBoxButtons bM = MessageBoxButtons.YesNo; DialogResult dR = MessageBox.Show("index.htm exists in this directory - won't overide it - exiting... Check and make sure you want to override it", "Prompt before Overide - Overide Yes/No", bM); // exit unless the user says yes if (dR != DialogResult.Yes) { return; } } DirectoryInfo di = new DirectoryInfo(textBox1.Text); FileInfo[] files = di.GetFiles("*.htm", SearchOption.AllDirectories); // gets all the htm & html files in the directory & subdirectories // First create FramePage / index file indexFile.WriteLineUTF8("<html><header><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\"><title>__index__</title>"); indexFile.WriteLineUTF8("<script> function op() { } </script>"); // see online docs if necessary // Construct the Frame indexFile.WriteLineUTF8("<frameset cols=\"25%,*\" frameborder=\"0\" framespacing=\"0\" border=\"0\">"); indexFile.WriteLineUTF8("<frame name=\"treeframe\" src=\"__outline__.htm\" >"); indexFile.WriteLineUTF8("<frame name=\"mainus\" src=\"" + files[0].Name + "\">"); indexFile.WriteLineUTF8("</frameset></header><body>"); // Write out Index For Show File indexForShowFile.WriteLineUTF8("<html><header><meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\"><title>Index File</title></head>"); indexForShowFile.WriteLineUTF8("<body>Select Table of Page From Table of Contents<br><br></body></html>"); // Now Create Outline File outlineFile.WriteLineUTF8("<html><header><title>Outline File</title><base target=\"mainus\"></header><body>"); foreach (FileInfo file in files) { // skip index file if already existed if (file.Name == "__index__.htm" || file.Name == "__outline__.htm" || file.Name == "index.htm") { continue; } // is it a frontpage extension dir? if (file.DirectoryName.Contains("_vti")) { continue; //if so, skip } string path = ""; // if it is a subdirectory? if (file.DirectoryName.Length > textBox1.Text.Length) { path = file.DirectoryName.Substring(textBox1.Text.Length + 1); // we want to omitt the \\ path = path.Replace('\\', '/'); // replace all backward slashes path += "/"; //it's a subdirectory so add this to the path so that we can display the file } outlineFile.WriteLineUTF8("<a href=\"" + Uri.EscapeUriString(path) + Uri.EscapeUriString(file.Name) + "\">" + file.Name + "</a><br><br>"); } outlineFile.WriteLineUTF8("</body></html>"); MessageBox.Show("__index__.htm and __outline__.htm created in target directory"); } else { MessageBox.Show("Folder specified is incorrect"); } }
public async void addFile(FileM file) { this._dataContext.Files.Add(file); await this._dataContext.SaveChangesAsync(); }