为我的日志管理器共享路径违规

本文关键字:路径 共享 管理器 我的 日志 | 更新日期: 2023-09-27 18:13:33

我使用这段代码保存日志在我的c# monotouch应用程序:

public static void  writeExeption(string message){
        string path= StorageClass .LogsPath ;
        string filepath= Path.Combine (path ,"Log.txt");
        if(!File.Exists (filepath )){
            using (StreamWriter sw = File.CreateText(filepath)) 
            {
                sw.WriteLine ("--------------------------------------------------------------------------" +
                              "--------------------");
                sw.WriteLine("blahblah...");
                sw.WriteLine ("--------------------------------------------------------------------------" +
                              "--------------------");
            }   
        }
        using (StreamWriter w = File.AppendText(filepath ))
        {
            Log(message , w);
        }
    }
    public static void Log(string logMessage, TextWriter w)
    {
        w.Write("'r'nLog Entry : ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongDateString());
        w.WriteLine("  :");
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine ("--------------------------------------------------------------------------" +
                      "--------------------");
    }

但是在应用程序中,我得到了这个错误:

 Sharing violation on path 'File Path'

为我的日志管理器共享路径违规

尝试在lock语句中添加附加数据的StreamWriter。首先,添加一个要引用的对象:

static object _locker = new object();

然后,修改writeExeption方法,锁定最后一条using语句:

lock (_locker)
{
    using (StreamWriter w = File.AppendText(filepath))
    {
        Log(message, w);
    }
}

如果这仍然不起作用,这意味着有其他应用程序正在使用您的文件。

似乎你在两个或多个地方访问一个文件(可能在不同的线程中)。

使用以下方法在多线程应用程序中读写文件以避免此类错误:

    /// <summary>
    /// Writes the file exclusively. No one could do anything with file while it writing
    /// </summary>
    /// <param name="path">Path.</param>
    /// <param name="data">Data.</param>
    public static void WaitFileAndWrite(string path, byte[] data)
    {
        while (true) {
            Stream fileStream = null;
            try {
                // FileShare.None is important: exclusive access during writing
                fileStream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None);
                fileStream.Write(data, 0, data.Length);
                break;
            } catch (IOException ex) {
                Console.WriteLine (ex);
                Thread.Sleep(10);
            } finally {
                if (fileStream != null) {
                    fileStream.Close();
                }
            }
        }
    }
    /// <summary>
    /// Waits the file and read.
    /// </summary>
    /// <returns>The file and read.</returns>
    /// <param name="fileName">File name.</param>
    public static byte [] WaitFileAndRead(string fileName)
    {
        byte[] result = null;
        if (File.Exists(fileName)) {
            while (true) {
                Stream fileStream = null;
                try {
                    fileStream = File.OpenRead(fileName);
                    var length = fileStream.Length;
                    result = new byte[length];
                    fileStream.Read(result, 0, Convert.ToInt32(length));
                    break;
                } catch (IOException ex) {
                    Console.WriteLine (ex);
                    Thread.Sleep(10);
                } finally {
                    if (fileStream != null) {
                        fileStream.Close();
                    }
                }
            }
        }
        return result;
    }
}

但你应该准确。如果有人打开文件进行读写操作而没有关闭它,这些方法将尝试无限打开。