开发者

c# How to access file if that file is processed by other process?

 pu开发者_JAVA百科blic static void WriteLine(string text)
    {
        StreamWriter log;

        if (!File.Exists(Filename))
        {
            log = new StreamWriter(Filename);
        }
        else
        {
            log = File.AppendText(Filename);
        }

while this method is processed, other process also call this method. There will be error occur "file has been acess by other process". How to solve this problem by waiting the previous process finish.


I think the op wants to wait until the filehandle is free to use and then write to the file. In this case you should try to get the filehandle, catch the exception and if the exception is because the file is accessed by another process then wait a short time and try again.

 public static void WriteLine(string text)
        {
            bool success = false;
            while (!success)
            {

                try
                {
                    using (var fs = new FileStream(Filename, FileMode.Append))
                    {
                        // todo: write to stream here

                        success = true;
                    }
                }
                catch (IOException)
                {
                    int errno = Marshal.GetLastWin32Error();
                    if(errno != 32) // ERROR_SHARING_VIOLATION
                    {
                        // we only want to handle the 
                        // "The process cannot access the file because it is being used by another process"
                        // exception and try again, all other exceptions should not be caught here
                        throw;
                    }

                Thread.Sleep(100);
                }
            }

        }


Both processes need to create a FileStream where they specify a FileShare mode of Write. You can then also drop the test whether the file exists, and just use the Append FileMode.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜