Click here to Skip to main content
15,916,379 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
C#
public static void WriteLogFile(string message)
       {
           Console.WriteLine(message);

           if (File.Exists("C:\\log.txt"))
           {
               using (StreamWriter SWriter = File.AppendText("C:\\log.txt"))
               {
                   SWriter.WriteLine(message);
               }
           }
           else
           {
               using (StreamWriter SWriter = File.CreateText("C:\\log.txt"))
               {

                   SWriter.WriteLine(message);
               }
           }
       }



This is my code. Could you please anyone tell me the reason for the error which i mentioned. Using statement usually dispose the object once it went out of scope, but i am getting the error.
Posted
Comments
BELGIUMsky 17-Apr-14 10:41am    
Did you try explicitly closing the streamwriter within your using statement? (for testing)?

Do you have the log file open with another application?
arunthangavel 17-Apr-14 10:42am    
no i am not explicitly closing the streamwriter withing using statement

No i am not opened the log file for another application
BELGIUMsky 17-Apr-14 10:48am    
ok sorry that i suggested it then
DamithSL 17-Apr-14 11:48am    
may be another process still accessing your file. Go to task manager and close all instants of your applications.
DamithSL 17-Apr-14 11:51am    
If you running multiple instances or reusing same text file, then your solution will not work. you need to find thread safe log solution. why don't you try lognet? http://stackoverflow.com/questions/4098409/thread-safety-of-log4net

1 solution

This is a very usual problem. Please see my recommendations in my past answer: how to compress the error 'it is already used by another process' in vb.net[^].

—SA
 
Share this answer
 
v2
Comments
Matt T Heffron 17-Apr-14 14:28pm    
Copy-n-paste error here, Sergey??
Sergey Alexandrovich Kryukov 17-Apr-14 14:34pm    
Exactly. Thank you very much, I'll fix it. fixed.
—SA
arunthangavel 18-Apr-14 1:07am    
Sorry Guys, i cant find the solution from your answers.
Sergey Alexandrovich Kryukov 18-Apr-14 1:57am    
What did you try?
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900