开发者

C# Creating a text file contains the error logs

I have created a text file to save the error in that created file. I have a button which, once pressed, generates an error which should be saved to the file. But if I press the button twice, it will overwrite the first error generated, because the contents of the file are overwritten. I want to gen开发者_Python百科erate a another separate file to save the new error. A new file should be generated for each new error.

Thanks in advance


Simple use: FileExists Method and then if it exists pick a new name. Alternatively you could just append to the file.

PSUDO:

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

This could be the perfect link for you How to Open and Append a log file


You can add time stamp in filename, in this case you would get new file each time.


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've had Int32.MaxValue files, but that'll take a while.

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

You may also want to consider using a more robust logging solution, such as log4net.


Creating file in C# is probably what you're looking for.


So you want to generate a unique file name for each error that occurs in your program? Probably the easiest way to accomplish this is to use the date/time when the error occured to name the file. In the function where you are writing to the file you will want to name the file like this:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜