我试图在我的程序中记录每个方法,我在 IIS 服务器上部署了应用程序,用户刚刚调用我说电子邮件功能不起作用,所以我基本上需要运行该应用程序,但将每个步骤记录到txt文件。
我声明以下为全局值:
StreamWriter writer = new StreamWriter("C:\\file.txt");
然后我在我的代码中像下面这样使用它:
Method 1
{
if (file1.HasFile)
{
writer.WriteLine("Has File");
}
}
方法二
private Boolean InsertUpdateData(SqlCommand cmd)
{
writer.WriteLine("Insert Started" + DateTime.Now.ToString());
}
所以在我的例子中,第一种方法运行良好,它写入了 Has File,但是当它进入第二种方法时,我发现文件已经打开,这是正确的,我该如何解决这个问题?
谢谢
全局值 - 在顶部声明
namespace WorkOrderManagement
{
public partial class CreateWorkOrder : System.Web.UI.Page
{
bool successfull;
string path;
string name;
string content;
string datas;
string ext;
bool affectedrows;
string seasonalsupervisor;
private string sLogFormat;
private string sErrorTime;
StreamWriter writer = new StreamWriter("C:\\file.txt");
最佳答案
我真的建议您放弃使用全局变量来表示流的想法,然后尝试在不同的方法中使用它。这在桌面应用程序中很简单,但在 ASP.NET 应用程序中要复杂得多。
有一些简单的替代方法可以自动写入您的日志文本并使文件保持解锁状态。
例如你可以有这样的方法
public static class Log
{
public static string _file = "log.txt";
public static object _locked = new object();
public static void AppendToLog(string text)
{
lock(_locked)
{
string path = Server.MapPath("~/APP_DATA");
File.AppendAllText(Path.Combine(path, _file), text + Environment.NewLine);
}
}
}
现在你可以调用日志写入
Log.AppendToLog("My message");
我想在这里强调两件重要的事情。首先我不写在服务器的根驱动器中。这是一种不好的做法,并且当您将 ASP.NET 应用程序部署在您无权使用站点根目录之外的任何内容的服务器中时,这总是问题的根源。因此,ASP.NET 系统在您的站点根目录下定义了一个名为 APP_DATA 的特定文件夹,您的应用程序应在其中具有读/写权限。 第二点要注意的是 lock 关键字的使用。这在像 ASP.NET 这样的环境中是必要的,在这种环境中,两个用户可以到达您需要写入公共(public)日志文件的代码点。正如 MSDN 所解释的那样
The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.
关于c# - 该进程无法访问文件 'C:\file.txt',因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515546/