Insertion data into text file exception - c#

I have written a code that crates a text file called contact and then try to store data and read data from it.
I have no problem in storing data but how can I store new data without override the oldest one?
and when I am finishing the insertion process an exception occurred : that my text file can not be accessed because it is being used by another process.
what should I do ??
here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace ConsoleApplication9
{
[Serializable]
class contact
{
string name;
string address;
string phonenumber;
string emailaddress;
public override string ToString()
{
return name + " " + address + " " + phonenumber + " " + emailaddress;
}
public void AddContent(string cname, string caddress, string cphone, string cemail)
{
name = cname;
address = caddress;
phonenumber = cphone;
emailaddress = cemail;
FileStream file = new FileStream("contact.txt", FileMode.OpenOrCreate, FileAccess.Write);
BinaryFormatter bin = new BinaryFormatter();
contact person = new contact();
person.name = cname;
person.address = caddress;
person.phonenumber = cphone;
person.emailaddress = cemail;
bin.Serialize(file, person);
file.Close();
Console.WriteLine(" added ");
}
public void viewContact
{
FileStream file = new FileStream("contact.txt", FileMode.Open, FileAccess.Read);
BinaryFormatter bin = new BinaryFormatter();
List<string> contact_list = new List<string>();
//while (file != null)
using (StreamReader read = new StreamReader("contact.txt"))
{
string temp = read.ReadToEnd();
contact_list.Add(temp);
} file.Close();
for (int i = 0; i < contact_list.Count; i++)
{
Console.WriteLine(contact_list[i]);
}
}
}//end of class

Use FileMode.Append to append to existing file

Related

computer cant find the right folder

im using c# in my web. i m trying to upload a video in my website and im almost succed but the computer go to folder'C:\Program Files (x86)\IIS Express\' insted of just C:\Users\Omer\source\repos\WebApplication12\WebApplication12\potg. im using the function Server.MapPath(folder) and yet its dont work. help pls?
c#
string path = "";
MyVideoHelper x = new MyVideoHelper();
bool deleteFile = false;
if ((video2.PostedFile != null) && (video2.PostedFile.ContentLength > 0))
{
path =x.SaveFileInFoder(video2.PostedFile, "potg", Server);
deleteFile = true;
}
string potg = "potg";
string command = "INSERT INTO videos (file) VALUES('"+x.ConvertFileToByte(potg)+"')";
MyAdoHelper.DoQuery("omerwatchdb.accdb", command);
Response.Redirect("potg.aspx");
Response.End();
if ((deleteFile) && (File.Exists(path))){File.Delete(path);}
library:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public class MyVideoHelper
{
public MyVideoHelper()
{
}
public byte[] ConvertFileToByte(string location)
{
byte[] video = null;
FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
video = br.ReadBytes((int)(fs.Length));
return video;
}
public string SaveFileInFoder(HttpPostedFile file, string folder, HttpServerUtility Server)
{
string location;
if (file != null && file.ContentLength > 0)
{
location = Server.MapPath(folder) + "\\" + System.IO.Path.GetFileName(file.FileName);
try
{
file.SaveAs(location);
}
catch (Exception ex)
{
location = ex.Message;
}
}
else
{
location = null;
}
return location;
}
}

Transfer files directly from FTP to Azure File Storage without keeping them locally in memory or disk

I have to transfer files from FTP to an Azure File Storage. My code works fine, but I'm transferring those files in memory which is not a best practice. So first I read the stream to an Byte array in memory. Then I upload the output to an Azure file storage.
Now I know it's better to do this asynchronicaly. But I don't know if this is possible and how to do it.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using System.Configuration;
using Microsoft.WindowsAzure.Storage.File;
using System.IO;
using Microsoft.Azure;
using System.Net;
namespace TransferFtpToAzure
{
class Program
{
public static void Main(string[] args)
{
List<FileName> sourceFileList = new List<FileName>();
List<FileName> targetFileList = new List<FileName>();
string targetShareReference = ConfigurationManager.AppSettings["AzureShare"];
string targetDirectoryReference = ConfigurationManager.AppSettings["Environment"] + "/" + Enums.AzureFolders.Mos + "/" + Enums.AzureFolders.In;
string sourceURI = (ConfigurationManager.AppSettings["FtpConnectionString"] + ConfigurationManager.AppSettings["Environment"].ToUpper() +"/"+ Enums.FtpFolders.Mos + "/").Replace("\\","/");
string sourceUser = ConfigurationManager.AppSettings["FtpServerUserName"];
string sourcePass = ConfigurationManager.AppSettings["FtpServerPassword"];
getFileLists(sourceURI, sourceUser, sourcePass, sourceFileList, targetShareReference, targetDirectoryReference, targetFileList);
Console.WriteLine(sourceFileList.Count + " files found!");
CheckLists(sourceFileList, targetFileList);
targetFileList.Sort();
Console.WriteLine(sourceFileList.Count + " unique files on sourceURI" + Environment.NewLine + "Attempting to move them.");
foreach (var file in sourceFileList)
{
try
{
CopyFile(file.fName, sourceURI, sourceUser, sourcePass, targetShareReference, targetDirectoryReference);
}
catch
{
Console.WriteLine("There was move error with : " + file.fName);
}
}
}
public class FileName : IComparable<FileName>
{
public string fName { get; set; }
public int CompareTo(FileName other)
{
return fName.CompareTo(other.fName);
}
}
public static void CheckLists(List<FileName> sourceFileList, List<FileName> targetFileList)
{
for (int i = 0; i < sourceFileList.Count; i++)
{
if (targetFileList.BinarySearch(sourceFileList[i]) > 0)
{
sourceFileList.RemoveAt(i);
i--;
}
}
}
public static void getFileLists(string sourceURI, string sourceUser, string sourcePass, List<FileName> sourceFileList, string targetShareReference, string targetDirectoryReference, List<FileName> targetFileList)
{
string line = "";
/////////Source FileList
FtpWebRequest sourceRequest;
sourceRequest = (FtpWebRequest)WebRequest.Create(sourceURI);
sourceRequest.Credentials = new NetworkCredential(sourceUser, sourcePass);
sourceRequest.Method = WebRequestMethods.Ftp.ListDirectory;
sourceRequest.UseBinary = true;
sourceRequest.KeepAlive = false;
sourceRequest.Timeout = -1;
sourceRequest.UsePassive = true;
FtpWebResponse sourceRespone = (FtpWebResponse)sourceRequest.GetResponse();
//Creates a list(fileList) of the file names
using (Stream responseStream = sourceRespone.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
line = reader.ReadLine();
while (line != null)
{
var fileName = new FileName
{
fName = line
};
sourceFileList.Add(fileName);
line = reader.ReadLine();
}
}
}
/////////////Target FileList
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//var test = fileClient.ListShares();
CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
if (fileShare.Exists())
{
CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
if (rootDirectory.Exists())
{
CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
if (customDirectory.Exists())
{
var fileCollection = customDirectory.ListFilesAndDirectories().OfType<CloudFile>();
foreach (var item in fileCollection)
{
var fileName = new FileName
{
fName = item.Name
};
targetFileList.Add(fileName);
}
}
}
}
}
public static void CopyFile(string fileName, string sourceURI, string sourceUser, string sourcePass, string targetShareReference, string targetDirectoryReference)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceURI + fileName);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(sourceUser, sourcePass);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
Upload(fileName, ToByteArray(responseStream), targetShareReference, targetDirectoryReference);
responseStream.Close();
}
catch
{
Console.WriteLine("There was an error with :" + fileName);
}
}
public static Byte[] ToByteArray(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
ms.Write(chunk, 0, bytesRead);
}
return ms.ToArray();
}
public static bool Upload(string FileName, byte[] Image, string targetShareReference, string targetDirectoryReference)
{
try
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudFileClient fileClient = storageAccount.CreateCloudFileClient();
//var test = fileClient.ListShares();
CloudFileShare fileShare = fileClient.GetShareReference(targetShareReference);
if (fileShare.Exists())
{
CloudFileDirectory rootDirectory = fileShare.GetRootDirectoryReference();
if (rootDirectory.Exists())
{
CloudFileDirectory customDirectory = rootDirectory.GetDirectoryReference(targetDirectoryReference);
if (customDirectory.Exists())
{
var cloudFile = customDirectory.GetFileReference(FileName);
using (var stream = new MemoryStream(Image, writable: false))
{
cloudFile.UploadFromStream(stream);
}
}
}
}
return true;
}
catch
{
return false;
}
}
}
}
If I understand you correctly, you want to avoid storing the file in memory between the download and upload.
For that see:
Azure function to copy files from FTP to blob storage.
Using Azure Storage File Share this is the only way it worked for me without loading the entire ZIP into Memory. I tested with a 3GB ZIP File (with thousands of files or with a big file inside) and Memory/CPU was low and stable. I hope it helps!
var zipFiles = _directory.ListFilesAndDirectories()
.OfType<CloudFile>()
.Where(x => x.Name.ToLower().Contains(".zip"))
.ToList();
foreach (var zipFile in zipFiles)
{
using (var zipArchive = new ZipArchive(zipFile.OpenRead()))
{
foreach (var entry in zipArchive.Entries)
{
if (entry.Length > 0)
{
CloudFile extractedFile = _directory.GetFileReference(entry.Name);
using (var entryStream = entry.Open())
{
byte[] buffer = new byte[16 * 1024];
using (var ms = extractedFile.OpenWrite(entry.Length))
{
int read;
while ((read = entryStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
}
}
}
}
}
}

its possible make a stream reader that Read 5 lines at a time instead of one?

I use a StreamReader but it only reads one line at a time.
My question is: Is it possible to change this behaviour so I can read more than one? For example: 5 lines at a time?
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
class example
{
public static void Main()
{
var path = "pruebastream.txt";
var path2 = "pruebastream2.txt";
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
using (StreamWriter outputFile = new StreamWriter(path2))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var text = ProcessLine(line);
outputFile.WriteLine(text);
}
}
}
static string ProcessLine(string text)
{
}
}
This might get downvoted a bit, but easier approach can be to just use 5 .ReadLine:
using (var sr = File.OpenText("1.txt"))
using (var sw = File.CreateText("2.txt"))
{
while (!sr.EndOfStream)
{
var s = sr.ReadLine() + "\r\n" + sr.ReadLine() + "\r\n" +
sr.ReadLine() + "\r\n" + sr.ReadLine() + "\r\n" + sr.ReadLine();
}
}
Otherwise, use counter variable if you don't want the extra newline characters after the last few lines.

String too small to store standard output of process

I direct the standard output/error of a process and store it in a string which I log to a file.
I have noticed that not all of the standard output is stored in the text file so I must be hitting the size limit of the string.
Does anyone know of an alternative which would help satisfy this issue?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Logging
{
class Logger
{
private FileStream file = null;
private StreamWriter writer = null;
public Logger(string _path)
{
if (!File.Exists(_path)) File.Create(_path).Dispose();
file = new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Write);
writer = new StreamWriter(file);
}
public void Log(string _text)
{
Console.WriteLine(_text);
using (file)
{
writer.WriteLine("[" + DateTime.Now + "] : " + _text);
}
}
}
}
using (file)
You just disposed your file. You can't write to it anymore.
The string type has a limit of 2GB.
Your handling of the file creation and disposal is causing you some difficulty.
Try this for a little cleaner logging code:
const string log = #"logfile path";
public void Log(string _text)
{
try
{
using (TextWriter tw = new StreamWriter(_path, true))
{
tw.WriteLine("[" + DateTime.Now + "] : " + _text);
}
}
catch (Exception)
{
throw;
}
}

Multipage PDF document from predefined template

I have a requirement to generate invoice reports in PDF using some predefined company templates. I am able to create/generate SINGLE PAGE PDF reports using iTextSharp.
Problem: The problem comes when the invoice statement spans MULTIPLE PAGES. I am not able to extend the report(invoice statement) to next(2nd) page. If all the data can not be accommodated on one page it should be written on 2nd page, while still using the company template.
The template is present at following path:
HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf")
I am using iTextSharp library to create documents. Below is the code used to generate the PDF:
public class pdfStatementController : Controller {
Models.DYNAMICS_EXTEntities _db = new Models.DYNAMICS_EXTEntities();
//
// GET: /pdfStatement/
public ActionResult SendPdfStatement(string InvoiceNumber) {
try {
InvoiceNumber = InvoiceNumber.Trim();
ObjectParameter[] parameters = new ObjectParameter[1];
parameters[0] = new ObjectParameter("InvoiceNumber", InvoiceNumber);
List<Models.Statement> statementList = new List<Models.Statement>();
statementList = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters).ToList<Models.Statement>();
pdfStatementController.WriteInTemplate(statementList);
return RedirectToAction("Invoice", "Invoice", new { id = statementList.FirstOrDefault().Customer_ID.ToString().Trim() });
} catch (Exception e) {
return View("Error");
}
}
public static void WriteInTemplate(List<Models.Statement> statementList) {
string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim();
string month = null;
string day = null;
string year = null;
PdfReader pdfReader = new PdfReader(
HostingEnvironment.MapPath(
"~/Content/InvoiceTemplate/invoiceTemplate.pdf"));
FileStream fileStream = new FileStream(
HostingEnvironment.MapPath(
"~/Content/reports/" + invoiceNumber + ".pdf"),
FileMode.Create);
PdfStamper pdfStamper = new PdfStamper(pdfReader, fileStream);
AcroFields pdfFields = pdfStamper.AcroFields;
pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper());
pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper());
pdfFields.SetField("CustomerId", statementList.FirstOrDefault().Customer_ID);
pdfFields.SetField("InvoiceNumber", statementList.FirstOrDefault().Invoice.ToString().Trim());
pdfFields.SetField("JobNumber", statementList.FirstOrDefault().JobNumber.ToString().Trim());
pdfFields.SetField("Caller", statementList.FirstOrDefault().Caller.ToString().Trim());
pdfStamper.FormFlattening = true; // generate a flat PDF
pdfStamper.Close();
pdfReader.Close();
}
}
Your code looks good and is only missing a couple of intermediate steps.
Since you're using the same PDF template for every page (when two or more pages need to be generated), instead of using a PdfStamper to add content directly to the Document, you use a PdfSmartCopy or PdfCopy object.
The PdfStamper is still needed. However, in this case it's used to create an in-memory (single) page filled with data as you as you iterate over your Models.Statement collection.
In other words, PdfSmartCopy/PdfCopy maintains your statements as a whole, (total pages) and PdfStamper is used as a buffer that adds your individual statements page-by-page to your PDF. Here's a simple working example HTTP hander (.ashx):
<%# WebHandler Language="C#" Class="copyFillTemplate" %>
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class copyFillTemplate : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpServerUtility Server = context.Server;
HttpResponse Response = context.Response;
Response.ContentType = "application/pdf";
// template used to test __this__ example;
// replace with __your__ PDF template
string pdfTemplatePath = Server.MapPath(
"~/app_data/template.pdf"
);
// this example's test data; replace with __your__ data collection
List<Statement> statementList = Statement.GetStatements();
// COPY FROM HERE
using (Document document = new Document()) {
// PdfSmartCopy reduces PDF file size by reusing parts
// of the PDF template, but uses more memory. you can
// replace PdfSmartCopy with PdfCopy if memory is an issue
using (PdfSmartCopy copy = new PdfSmartCopy(
document, Response.OutputStream)
)
{
document.Open();
// used to test this example
int counter = 0;
// generate one page per statement
foreach (Statement statment in statementList) {
++counter;
// replace this with your PDF form template
PdfReader reader = new PdfReader(pdfTemplatePath);
using (var ms = new MemoryStream()) {
using (PdfStamper stamper = new PdfStamper(reader, ms)) {
AcroFields form = stamper.AcroFields;
// replace this with your field data for each page
form.SetField("title", counter.ToString());
stamper.FormFlattening = true;
}
reader = new PdfReader(ms.ToArray());
// add one page at a time; assumes your template is only one page.
// if your template is more than one page you will need to
// call GetImportedPage() for each page in your template
copy.AddPage(copy.GetImportedPage(reader, 1));
}
}
}
// COPY TO HERE
}
}
public bool IsReusable { get { return false; } }
public class Statement {
public string FieldName, FieldValue;
public static List<Statement> GetStatements() {
List<Statement> s = new List<Statement>();
for (int i = 0; i < 5; ++i) {s.Add(new Statement());}
return s;
}
}
}
Hopefully the inline comments help. And you obviously need to remove replace some parts I used to test the example code.
Though the last answer is a very good one and helped me to solve my problem, i am putting it here to sum up the question.
Problem: I had a scenario to generate multipage pdf document in Company provided template. Needed to generate invoice statements and attach them to email via Microsoft outlook email Client.
I use MVC3, ASP.NET 4.0, Entity Framework
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Data;
using System.Data.Objects;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
namespace InvoiceSearchTool.Controllers
{
public class pdfStatementController : Controller
{
Models.DYNAMICS_EXTEntities _db = new Models.DYNAMICS_EXTEntities();
//
// GET: /pdfStatement/
public ActionResult SendPdfStatement(string InvoiceNumber)
{
try
{
InvoiceNumber = InvoiceNumber.Trim();
List<Models.Statement> statementList = new List<Models.Statement>();
//this is if you use entity framework
{
ObjectParameter[] parameters = new ObjectParameter[1];
parameters[0] = new ObjectParameter("InvoiceNumber", InvoiceNumber);
statementList = _db.ExecuteFunction<Models.Statement>("uspInvoiceStatement", parameters).ToList<Models.Statement>();
}
//others can simply use line like
//statementList = GetStatementList(inviceNumber);
pdfStatementController.WriteInTemplate(statementList);
return RedirectToAction("Invoice", "Invoice", new { id = statementList.FirstOrDefault().Customer_ID.ToString().Trim() });
}
catch (Exception e)
{
return View("Error");
}
}
public static void WriteInTemplate(List<Models.Statement> statementList)
{
try
{
string invoiceNumber = statementList.FirstOrDefault().Invoice.ToString().Trim();
using (Document document = new Document())
{
FileStream fileStream = new FileStream(HostingEnvironment.MapPath("~/Content/reports/" + invoiceNumber + ".pdf"), FileMode.Create);
using (PdfSmartCopy smartCopy = new PdfSmartCopy(document, fileStream))
{
document.Open();
PdfReader pdfReader = new PdfReader(HostingEnvironment.MapPath("~/Content/InvoiceTemplate/invoiceTemplate.pdf"));
using (var memoryStream = new MemoryStream())
{
using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
{
string month = null;
string day = null;
string year = null;
AcroFields pdfFields = pdfStamper.AcroFields;
{//billing address
pdfFields.SetField("BillToCompany", statementList.FirstOrDefault().BillToCompany.ToString().Trim().ToUpper());
pdfFields.SetField("BillToContact", statementList.FirstOrDefault().BillToContact.ToString().Trim().ToUpper());
pdfFields.SetField("ShipToCompany", statementList.FirstOrDefault().ShipToCompany.ToString().Trim().ToUpper());
pdfFields.SetField("ShipToContact", statementList.FirstOrDefault().ShipToContact.ToString().Trim().ToUpper());
pdfFields.SetField("PONumber", statementList.FirstOrDefault().PurchaseOrderNo.ToString().Trim());
pdfFields.SetField("OrderNumber", statementList.FirstOrDefault().Order_Number.ToString().Trim());
pdfFields.SetField("ShippingMethod", statementList.FirstOrDefault().Shipping_Method.ToString().Trim());
pdfFields.SetField("PaymentTerms", statementList.FirstOrDefault().Payment_Terms.ToString().Trim());
}
pdfStamper.FormFlattening = true; // generate a flat PDF
}
pdfReader = new PdfReader(memoryStream.ToArray());
smartCopy.AddPage(smartCopy.GetImportedPage(pdfReader, 1));
}
}
}
emailController.CreateMessageWithAttachment(invoiceNumber);
}
catch (Exception e)
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.Net;
using System.Net.Mail;
using System.Web.Hosting;
using System.Net.NetworkInformation;
using System.Data.Objects;
namespace InvoiceSearchTool.Controllers
{
public class emailController : Controller
{
//
// GET: /email/
public static void CreateMessageWithAttachment(string invoiceNumber)
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem email = (Outlook.MailItem)(oApp.CreateItem(Outlook.OlItemType.olMailItem));
Models.DYNAMICS_EXTEntities _db = new Models.DYNAMICS_EXTEntities();
string recipient = null;
string messageBody = null;
#region set email recipients
{
ObjectParameter[] parameters = new ObjectParameter[1];
parameters[0] = new ObjectParameter("InvoiceNumber", invoiceNumber);
List<Models.EmailAddress> emailList = _db.ExecuteFunction<Models.EmailAddress>("uspGetEmailAddress", parameters).ToList<Models.EmailAddress>();
if(!string.IsNullOrEmpty(emailList[0].Email.ToString()))
recipient = emailList[0].Email.ToString().Trim();
else
recipient = " ";
email.Recipients.Add(recipient);
}
#endregion
//email subject
email.Subject = "Invoice # " + invoiceNumber;
#region set email Text
{
Models.EmailText emailText = _db.ExecuteFunction<Models.EmailText>("uspEmailText").SingleOrDefault();
messageBody = emailText.EmailTextLine1.ToString().Trim() + "\n\n\n\n\n\n\n\n\n";
messageBody += emailText.EmailTextLine2.ToString().Trim() + "\n";
messageBody += emailText.EmailTextLine3.ToString().Trim();
email.Body = messageBody;
}
#endregion
#region email attachment
{
string fileName = invoiceNumber.Trim();
string filePath = HostingEnvironment.MapPath("~/Content/reports/");
filePath = filePath + fileName + ".pdf";
fileName += ".pdf";
int iPosition = (int)email.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Attachment oAttach = email.Attachments.Add(filePath, iAttachType, iPosition, fileName);
}
#endregion
email.Display();
//uncomment below line to SendAutomatedEmail emails atomaticallly
//((Outlook.MailItem)email).Send();
}
catch (Exception e)
{
}
}

Categories

Resources