Answer the question
In order to leave comments, you need to log in
How to avoid Unhandled exception of type 'System.IO.IOException' error in mscorlib.dll?
Hello, sometimes this error occurs:
Unhandled exception of type "System.IO.IOException" in mscorlib.dll
The code itself:
using System;
using System.IO;
namespace TurboBotNew
{
public static class Log
{
static string s_logFile = System.IO.Directory.GetCurrentDirectory() + "\\log.txt";
static int i_lastLog = 0;
public static void Write(string message)
{
string TimeNow = DateTime.Now.ToString("HH:mm:ss");
message = "[" + TimeNow + "] " + message + "\n";
File.AppendAllText(s_logFile, message);
}
public static void Close()
{
if (System.IO.File.Exists(s_logFile))
System.IO.File.Delete(s_logFile);
}
public static string Read(string s_log)
{
if (!System.IO.File.Exists(s_logFile))
Write("Создание лога");
var mass = System.IO.File.ReadAllLines(s_logFile);
string s_message = "";
for (int i = mass.Length - 1; i > i_lastLog; i--)
{
s_message = mass[i] + Environment.NewLine + s_message;
}
i_lastLog = mass.Length - 1;
return s_log + s_message;
}
}
}
Answer the question
In order to leave comments, you need to log in
The error occurs because you are trying to open the log file from multiple threads at the same time. Or you just opened it in a text editor at the same time.
PS
Tip number 1: discover NLog
Tip number 2: never do this in a loop
s_message = mass[i] + Environment.NewLine + s_message;
- for such things there is StringBuilder which works faster. s_message = string.Join(Environment.NewLine, mass)
Use StreamWriter to write.
Opened once at the first attempt to write and closed before the end of the program.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question