我的logmanager在路径上共享违规

时间:2013-05-15 09:10:17

标签: c# file logging xamarin.ios

我正在使用此代码在may 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'

2 个答案:

答案 0 :(得分:1)

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

使用这些方法读取/写入多线程应用程序中的文件以避免此类错误:

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

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

答案 1 :(得分:1)

尝试添加以附加StreamWriter,并将数据附加到lock语句中。 首先,添加一个对象来引用:

static object _locker = new object();

然后,通过锁定最后writeExeption语句来修改using方法:

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

如果仍然无效,则表示其他一些应用程序正在使用您的文件。如果它有效,则意味着您正在登录多个线程。