我是Windows服务的新手。
我遇到了一些问题: -
我已经创建了一个发送简单电子邮件的服务,现在我已经更改了代码以发送带有模板的电子邮件,但它无效。
错误: - "服务错误:10/04/2017 07:40:00 PM无法找到路径的一部分' C:\ Windows \ system32 \〜\付款-Receipt.htm'&#34 ;.
File.ReadAllText不是Server.MapPath的替代品所以应该使用什么?
private void SchedularCallback(object e)
{
try
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("getAllInvoices"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
foreach (DataRow row in dt.Rows)
{
string name = row["FirstName"].ToString();
string email = row["EmailId"].ToString();
long InvoiceId = Convert.ToInt64(row["InvoiceId"].ToString());
string amount = row["SettledAmount"].ToString();
WriteToFile("Trying to send email to: " + name + " " + email);
string body = this.createEmailBody(name, "Please check your account Information", amount);
using (MailMessage mm = new MailMessage(ConfigurationManager.AppSettings["UserName"], email))
{
mm.Subject = "Package Changed";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = ConfigurationManager.AppSettings["UserName"];
credentials.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mm);
}
}
this.ScheduleService();
}
catch (Exception ex)
{
WriteToFile("Service Error on: {0} " + ex.Message + ex.StackTrace);
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService"))
{
serviceController.Stop();
}
}
}
private string createEmailBody(string userName, string title, string amount)
{
string body = string.Empty;
string originalTemplate = File.ReadAllText(@"~\Payment-Receipt.htm");
using (StreamReader reader = new StreamReader(originalTemplate))
{
body = reader.ReadToEnd();
}
body = body.Replace("{FirstName}", userName); //replacing the required things
body = body.Replace("{Amount}", amount);
return body;
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
答案 0 :(得分:0)
我相信可以使用Visual Studio 2015调试服务。如果您在远程服务器上运行,则需要在端点上安装远程调试工具。据我所知,您需要将服务作为自己的进程运行(它不能在svchost内部托管),但我通常在尝试部署到生产系统之前在自己的进程内单独运行服务。只要您不在生产系统上运行此服务,运行远程调试工具应该没问题。如果该过程是本地的,那么您应该能够只附加到该过程。
您收到的错误是因为您正在尝试读取相对路径。我会在配置文件中粘贴路径,然后阅读。如果打印到Environment.CurrentDirectory
属性的调试文件,您将看到您的服务正在Windows系统目录中运行。