我有一个方法
private string sLogFormat;
private string sErrorTime;
public void CreateLogFile(string path, string msg)
{
//sLogFormat used to create log files format :
// dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
//this variable used to create log filename format "
//for example filename : ErrorLogYYYYMMDD
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear + sMonth + sDay;
StreamWriter sw = new StreamWriter(path + sErrorTime, true);
sw.WriteLine(sLogFormat + msg);
sw.Flush();
sw.Close();
}
另一个方法run()触发Onchanged处理程序(当文件夹内容更精确地更改时触发) 这里
public static void Run()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:/model_RCCMREC";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// watch wav files.
watcher.Filter = "*.wav";
// Add event handlers.
watcher.Created += new FileSystemEventHandler(OnChanged);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
和OnChanged处理程序为
public static void OnChanged(object source, FileSystemEventArgs e)
{
try
{
//access last folder(newly created one is suposedly at last position)
var directory = new DirectoryInfo("C:/model_RCCMREC");
var myFile = (from f in directory.GetFiles() orderby f.LastWriteTime descending select f).First();
//2.Split the file name.
}
catch
{
//I WANT TO ACCESS THE METHOD CreateLogFile(x,y) HERE
}
}
我无法正常从OnChanged处理程序访问方法CreateLogFile()。如何访问它?
答案 0 :(得分:1)
似乎OnChanged应该是非静态的。通常只有特定实例才会调用OnChanged。这是因为某些事物发生变化的knolage在它自己的实例中被包围了。从OnChanged中移除静电,你就可以了。
或者如果你不能/不想让你的OnChanged非静态,你可以使你的CreateLogFile静态,我没有看到任何理由在你的方法之外判断你的变量:
public static void CreateLogFile(string path, string msg)
{
string sLogFormat;
string sErrorTime;
//sLogFormat used to create log files format :
// dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
//this variable used to create log filename format "
//for example filename : ErrorLogYYYYMMDD
string sYear = DateTime.Now.Year.ToString();
string sMonth = DateTime.Now.Month.ToString();
string sDay = DateTime.Now.Day.ToString();
sErrorTime = sYear + sMonth + sDay;
StreamWriter sw = new StreamWriter(path + sErrorTime, true);
sw.WriteLine(sLogFormat + msg);
sw.Flush();
sw.Close();
}
答案 1 :(得分:0)
你有两种方法:
1-如果您的Logger类是非静态的,请使用YourLoggerClass创建一个新的记录器对象log = new YourLoggerClass();做空洞
2-让您的Logger类保持静态,这样您就可以在任何地方轻松使用它:
private static string sLogFormat;
private static string sErrorTime;
public static void CreateLogFile(string path, string msg)
{
...