[英]How to write text to txt file in web service using c#?
我有一个Web服务,该服务从某些客户端向sql插入数据。我尝试将插入的行和任何Exception写入txt文件。
void WriteLog(string Log)
{
string FileName= "D:\\MyLogs.txt";
StreamWriter obj;
obj= new StreamWriter(FileName);
obj.WriteLine(DateTime.Now.ToString() + " " + Log);
obj.Close();
}
int row;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
SqlCommand cmd = new SqlCommand();
[WebMethod]
public int InsertTable(int Age) {
try {
con.Open();
cmd.CommandText=@"Insert into Table(Age) values(@Age)";
cmd.Parameters.Add(new SqlParameter("Age", SqlDbType.Int, 32, "Age"));
cmd.Parameters["Age"].Value = Age;
cmd.Connection = con;
cmd.ExecuteNonQuery();
row = cmd.ExecuteNonQuery();
WriteLog(row.ToString());
}
catch (Exception ex) {
WriteLog(ex.ToString());
}
finally {
con.Close();
con.Dispose();
cmd.Dispose();
}
return row;
}
我收到此错误:'D:\\ MyLogs.txt'对该路径的访问被拒绝。
由于运行asp.net的用户没有必要的权限来写入D:驱动器,因此您将获得安全例外。 使用以下命令获取应用程序中的可写路径。
private void WriteLog(string log)
{
string fileName= HttpContext.Current.Request.MapPath("MyLogs.txt");
StreamWriter sw = new StreamWriter(fileName);
sw.WriteLine(DateTime.Now.ToString() + " " + log);
sw.Close();
}
此方法将为您提供运行(或部署)应用程序的路径。 例如:您将应用程序部署到“ c:\\ inetpub \\ www \\ app1”,然后将写入“ c:\\ inetpub \\ www \\ app1 \\ MyLogs.txt”。 无论您的项目在哪里,它都会在您的开发机器中发生变化。
当然,此方法会重写每个日志,因此MyLogs.txt仅包含一个日志。 使用以下内容附加到您的日志文件。
private void WriteLog(string log)
{
string fileName= HttpContext.Current.Request.MapPath("MyLogs.txt");
using (StreamWriter sw = File.AppendText(fileName))
{
sw.WriteLine(DateTime.Now.ToString() + " " + log);
}
}
当然,您可以授予运行用户“ D:驱动器”的必要权限,但我建议您反对。 您的应用程序应在没有其他特权的情况下运行。
您需要确保运行线程的凭据可以访问该文件。 尝试赋予IUSR对该文件具有读写执行权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.