3

I'm using this code for saving logs in may C# monotouch application:

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 ("--------------------------------------------------------------------------" +
                      "--------------------");
    }

But in the application I get this error:

 Sharing violation on path 'File Path'
4

2 回答 2

1

Seems like you're accessing one file in two or more places (could be in different threads).

Use these methods to read/write files in multi-thread apps to avoid such error:

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

Yet you should be accurate. If someone open file for read/write operations and don't close it, these method will try to open infinitely.

于 2013-05-15T09:21:49.057 回答
1

Try adding to enclose the StreamWriter which appends the data in a lock statement. First, add an object to refer to:

static object _locker = new object();

Then, modify the writeExeption method by locking the last using statement:

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

If this still doesn't work, it means that some other application is using your file. If it works, it means that you are logging on multiple threads.

于 2013-05-15T10:24:43.680 回答