S
S
skvoshiz2015-01-24 05:12:22
Programming
skvoshiz, 2015-01-24 05:12:22

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
8057d4a2bdd344c9b84fae39f37755ae.JPG
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;
        }
    }
}

How to avoid this error in this code?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mayorovp, 2015-01-26
@skvoshiz

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.
Tip number 3: Better yet, instead of such loops, use a convenient method
s_message  = string.Join(Environment.NewLine, mass)

Tip #4: Better yet, use File.ReadAllText instead of File.ReadAllLines in these cases.

A
Alexander Taratin, 2015-01-24
@Taraflex

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 question

Ask a Question

731 491 924 answers to any question