Avatar of patd1
patd1Flag for United States of America

asked on 

create file and append it

I want to catch exceptions in a log file. I want to name my log file by date. If the file exists, it should append to it, if file does not exist, it should create one. I tried the following code but get error access to path is denied. I have shared the logs folder and given full control to every one. Please suggest what needs to be done.

I am getting the correct FileName as 11-11-2010.txt and Fullname (with path) as \\myserver\Projects\Results\Logs\11-11-2010.txt

Error: Access to the path '\\myserver\Projects\Results\Logs\11-11-2010.txt' is denied.

Thank You
public void WriteLog(string TextStr)
        {
            string FilePath = ConfigurationManager.AppSettings["LogPath"].ToString();
            
            //Set Filename By Date
            string FileName = DateTime.Now.ToString("MM-dd-yyyy") + ".txt";
            string FullName = FilePath + FileName;
            
            //if file does not exist, create one
            if (!File.Exists(FullName))
            {
                FileStream fileStream = new FileStream(@FullName, FileMode.Append);
            }

            StreamWriter SW;
            SW = File.AppendText(FullName);
            SW.WriteLine(TextStr);
            SW.Close();
        }

Open in new window

C#

Avatar of undefined
Last Comment
patd1
ASKER CERTIFIED SOLUTION
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Miguel Oz
Miguel Oz
Flag of Australia image

Your porlbem is that multiple threads or processes are trying to access your fiel at the same time.
You need to call your file using a lock or a mutex:
use lock if your program is multithreaded.
public void WriteLog(string TextStr)
        {
            string FilePath = ConfigurationManager.AppSettings["LogPath"].ToString();
           
            //Set Filename By Date
            string FileName = DateTime.Now.ToString("MM-dd-yyyy") + ".txt";
            string FullName = FilePath + FileName;
           
            //check if file exists, else create one
lock(this)
{
            FileStream fileStream = new FileStream(@FullName, FileMode.Append);
            StreamWriter SW;
            SW = File.AppendText(FullName);
            SW.WriteLine(TextStr);
            SW.Close();
}
        }


else use mutex
http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx

Alternatives: use Trace class and specify your file, log framework (log4net)
http://stackoverflow.com/questions/1260157/whats-the-most-widely-used-logging-framework-in-c

Avatar of patd1
patd1
Flag of United States of America image

ASKER

Another small problem though:
For the new line character I am adding "\\n" to the string, but it is simply writing \n to the file. what do I do to make it write a new line character?

Thanks
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

When you put two backslashes together it means "interpret this as a single backslash character, not an escape sequance"
So "\\n" = \n
and "\n" = newline
But, you probably want "\r\n" which is the normal line termination sequence in Windows, or you can use Environment.NewLine - e.g. WriteLine("Hello World!" + Environment.NewLine);
Avatar of patd1
patd1
Flag of United States of America image

ASKER

I tried both "\r\n" and Environment.NewLine
Both write \n in my text file
see example:
\nMain Method In ResultGenerator\nCaseNo not passed in.\nSystem.IndexOutOfRangeException: Index was outside the bounds of the array.
   at ResultGenerator.ResultGenerator.Main(String[] args) in E:\Projects\ResultGenerator\ResultGenerator.cs:line 20
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

If you start a string with "@" then no escape sequences are recognized.
e.g.
@"Hello\r\nWorld" = Hello\r\nWorld
"Hello\r\nWorld" = Hello <newline> World
I recommend you use the String.Format method,
string message = String.Format("{0}\r\n{1}\r\n{2}", "Main Method in ResultGen", "CaseNo not passed", ex.Message);
Avatar of patd1
patd1
Flag of United States of America image

ASKER

mas_oz2003:
Thanks for pointing me to alternate soultions for logging. Is it a good idea to write to OS event log?
Any disadvantages?
C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo