Wait while file write in C#
How to wait for some time while writing to a file.
I am appending some text in log file, its giving error as Some other process using this file.
How i have to wait untill its free.
ambarisha.kn
Junior Poster in Training
66 posts since Jun 2008
Reputation Points: 25
Solved Threads: 0
What logging framework are you using that's giving you these problems?
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
Here, how i am writing log to a file.
Its giving error only for some time. It may or may not give error as "Some other process using this file".
How to rectify this. Is it possible to wait untill other process release this file.
public void WriteLog(LogType type, LogStatus status, string message, params object[] args)
{
DateTime now = DateTime.Now;
string path = GetPath(type, now);
string appname;
string usrname;
if (AppService.Provider.CurrentAppType == null)
appname = "-";
else
appname = AppService.Provider.CurrentAppType.ToString();
if (UserService.Provider.CurrentUser == null)
usrname = "-";
else
usrname = UserService.Provider.CurrentUser.Name;
appname = (appname + new string(' ', 10)).Substring(0, 10);
usrname = (usrname + new string(' ', 16)).Substring(0, 16);
string line = now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture) + " " +
status.ToString().Substring(0, 1) + " " +
appname + " " +
usrname + " " +
string.Format(CultureInfo.InvariantCulture, message, args) + Environment.NewLine;
lock (_lck)
{
File.AppendAllText(path, line);
#if DEBUG
Console.Write(line);
#endif
}
}
ambarisha.kn
Junior Poster in Training
66 posts since Jun 2008
Reputation Points: 25
Solved Threads: 0
Use log4net or NLog or some other framework for your logging.
Rashakil Fol
Super Senior Demiposter
2,658 posts since Jun 2005
Reputation Points: 1,135
Solved Threads: 177
dont know how to use. tell me how?
ambarisha.kn
Junior Poster in Training
66 posts since Jun 2008
Reputation Points: 25
Solved Threads: 0
You should only get the some other process is using that file if you're trying to open it, so as other have said open it, dont close it until you're done with it. Then there is no major delay to writing the file.
LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190