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.

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
            }
        }

Using a while loop arround the code open and write to the file.
Suggestion, put that code into another thread, so if it can't write out yet. Just sleep for one sec and try again. Something like this could do a dirty trick;
writtenOut = false;
while writtenOut=false
{
open file
if could open file
write to file
close file;
writtenOut=true;
sleep(1000);
}

Just make sure you close the stream...

Else , like hieuuk said,

do the

Thread.sleep(1000) // 1 second

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.

so as other have said open it, dont close it until you're done with it

I'd not recommend this in practice. If you open it and just hold on to it, what other process is now failing because you're holding onto resources? How about doing some research to find out what other process is using the file? If it's your own code doing it, then there's probably a bug in there somewhere of not releasing it properly that needs to be corrected. I'd look at something like HandleEx from sysinternals to determine what is holding onto the file.

-Nelis

This article has been dead for over six months. Start a new discussion instead.