2

Have a test class that creates log files that I write to. I want to be able to add text to the file throughout my program by referencing the LogErrors method of the class.

public class test
{
public static string errorFileName = DateTime.Now.ToString("yyyy-MM-dd") + "testerrors.csv";
public static StreamWriter errorfile =  new StreamWriter("c:\" + @"\" + errorFileName, true);


  public static void LogErrors(string error, string record)
  {
    test.errorfilewriter.WriteLine( error + "," +  record );
  }
}

Here is where I reference the class to append records to the file: If an error is encountered in my program I want to reference the method then add that line of text to the file

test.LogErrors("INVALID RECORD", string.Join(",",line));

At that line I get this error:

The type initializer for program.Test threw an excpetion.
INNER EXCEPTION: The process cannot access the file c:\2013-10-21testerrors.csv because it is being used by another process. 

The file was just created during this program so it does not exist yet and is not opened somewhere else.

EDIT:

public class test
{

   public static string errorFileName = DateTime.Now.ToString("yyyy-MM-dd") + "testERRORS.csv";
   private static object _lockObj = new Object();

  public static void LogErrors(string error, string record)
    {
        lock (_lockObj)
        {
            File.AppendAllText(Logging.errorFileName, error + "-" + record);
            //File.AppendAllLines does not exist in .NET 3.5
        }
    }

   test.LogErrors("INVALID",line));

I get past the test.LogError line and it goes to the test class but if I stop the program after it writes that line to test the file. Nothing is in the file Also can I use the the lock object for more than one file. As I'm creating a bunch of log files in this test class. How does the program know where to place the files like the c:/ as the streamwriter was declaring that.

4

2 に答える 2

0

ファイルが 2 つの異なるスレッドによって開かれようとしているため、ロックの問題が発生している可能性があります。

この作業を行うスレッドセーフなプログラムはたくさんあります。

例: http://nlog-project.org/

于 2013-10-22T15:02:50.540 に答える