C # Creating a text file contains error logs

I created a text file to save the error in this created file. I have a button that, after clicking, generates an error that should be saved in a file. But if I double-click the button, it will overwrite the first error created, because the contents of the file will be overwritten. I want to create another separate file to save a new error. For each new error, a new file must be created.

Thanks in advance

+3
source share
5 answers
private void SaveErrorMessage(string errorMessage)
{
    string errorFile = null;
    for( int x = 0; x < Int32.MaxValue; ++x )
    {
        errorFile = string.Format(CultureInfo.InvariantCulture, "error-{0}.txt", x);
        if( !System.IO.File.Exists(errorFileTest) )
        {
            break;
        }
    }

    File.WriteAllText(errorFile, errorMessage);
}

This will overwrite the last file after you have the Int32.MaxValue files, but it will take some time.

An alternative (and probably better) approach would be to simply add to the file rather than create a new one.

, log4net.

+1

: FileExists, , , . .

PSUDO:

public string checkFileName(string fileName){
  if(File.Exists(fileName)){
    /Pick a new one
    newFileName=  fileName + DateTime.Now.ToLongDateString()
    return checkFileName(newFileName)
   }
   return fileName
}

+2

filename, .

+2

# - , , , .

+1

So, you want to create a unique file name for each error that occurs in your program? Probably the easiest way to achieve this is to use the date / time when the error occurred to name the file. In the function where you are writing the file, you will want to name the file as follows:

string filename = LogPath + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".err";

Where LogPath is the path to the folder where you want to write the error files.

+1
source

All Articles