0

I'm writing small program which is supposed to count entropy, get info about the file etc. But I've got the problem with a thing which should be actually very simple.

I can't append text to txt file, and I don't even know why. I tried TextWriter, StreamWriter, File.AppendAllText etc. and none of them are working - I don't know why.

Here is the piece of code because of which I go nuts:

string pathx = Environment.CurrentDirectory + "//confusio.txt";
if (File.Exists(pathx))
{
    File.Delete(pathx);
    File.Create(pathx);
}
else
{
    File.Create(pathx);
}

string all = null;
all += "Confusio log file\n";
all += "Log created: " + DateTime.Now.ToLongDateString();
all += " User: " + Environment.UserName.ToString() + "\n\n\n";
all += "-=*( LOG )*=-\n";
all += ("Full name: " + full + '\n');
all += ("Size: " + size + " (bytes)\n");
all += ("Creation time: " + creation_time + '\n');
all += ("MD5: " + md5 + '\n');
all += ("SHA1: " + sha1 + '\n');
all += ("SHA256: " + sha256 + '\n');
all += ("Entropy: " + ShannonEntropy(buff) + '\n');
all += ("Last Write: " + lastWrite + '\n');
all += ("Last access: " + lastAccess + '\n');
all += ("Is read only: " + isReadOnly + '\n');
Console.Write(all); //for debugging
Console.ReadKey();  //for debugging
TextWriter twrt = new StreamWriter(@pathx, true);
twrt.Write(all); 
twrt.Close();
Console.WriteLine("Log file created at: " + pathx);
Console.ReadKey();
René Vogt
  • 43,056
  • 14
  • 77
  • 99
camed_
  • 1
  • 2
    What is there eeor you get? What is the command that throws the error? – SimSimY Mar 06 '16 at 17:37
  • A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll it works up to Console.ReadKey(), but then it just closes, there is no more output (no "Log file created at:") – camed_ Mar 06 '16 at 17:41
  • 1
    Your problem is the File.Create call. This call keeps the file locked after the creation. You should get the Stream from that call and use it when you create the StreamWriter. Or just drop it and let the StreamWriter create the file for you – Steve Mar 06 '16 at 17:41

0 Answers0